Regex matching numbers and decimals

后端 未结 5 1414
深忆病人
深忆病人 2020-12-06 10:53

I need a regex expression that will match the following:

.5
0.5
1.5
1234

but NOT

0.5.5
absnd (any letter character or space         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 11:20

    Here's a much simpler solution that doesn't use any look-aheads or look-behinds:

    ^\d*\.?\d+$
    

    To clearly understand why this works, read it from right to left:

    • At least one digit is required at the end.
      7 works
      77 works
      .77 works
      0.77 works
      0. doesn't work
      empty string doesn't work
    • A single period preceding the digit is optional.
      .77 works
      77 works
      ..77 doesn't work
    • Any number of digits preceding the (optional) period. .77 works
      0.77 works
      0077.77 works
      0077 works

    Not using look-aheads and look-behinds has the added benefit of not having to worry about RegEx-based DOS attacks.

    HTH

提交回复
热议问题