Regex allow digits and a single dot

后端 未结 5 729
难免孤独
难免孤独 2020-11-30 05:00

What would be the regex to allow digits and a dot? Regarding this \\D only allows digits, but it doesn\'t allow a dot, I need it to allow digits and

5条回答
  •  执念已碎
    2020-11-30 05:27

    If you want to allow 1 and 1.2:

    (?<=^| )\d+(\.\d+)?(?=$| )
    

    If you want to allow 1, 1.2 and .1:

    (?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )
    

    If you want to only allow 1.2 (only floats):

    (?<=^| )\d+\.\d+(?=$| )
    

    \d allows digits (while \D allows anything but digits).

    (?<=^| ) checks that the number is preceded by either a space or the beginning of the string. (?=$| ) makes sure the string is followed by a space or the end of the string. This makes sure the number isn't part of another number or in the middle of words or anything.

    Edit: added more options, improved the regexes by adding lookahead- and behinds for making sure the numbers are standalone (i.e. aren't in the middle of words or other numbers.

提交回复
热议问题