Regex matching numbers and decimals

后端 未结 5 1401
深忆病人
深忆病人 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:10

    This is a fairly common task. The simplest way I know of to deal with it is this:

    ^[+-]?(\d*\.)?\d+$
    

    There are also other complications, such as whether you want to allow leading zeroes or commas or things like that. This can be as complicated as you want it to be. For example, if you want to allow the 1,234,567.89 format, you can go with this:

    ^[+-]?(\d*|\d{1,3}(,\d{3})*)(\.\d+)?\b$
    

    That \b there is a word break, but I'm using it as a sneaky way to require at least one numeral at the end of the string. This way, an empty string or a single + won't match.

    However, be advised that regexes are not the ideal way to parse numeric strings. All modern programming languages I know of have fast, simple, built-in methods for doing that.

    0 讨论(0)
  • 2020-12-06 11:18

    This could work:

    ^(?:\d*\.)?\d+$
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-06 11:34

    Nobody seems to be accounting for negative numbers. Also, some are creating a capture group which is unnecessary. This is the most thorough solution IMO.

    ^[+-]?(?:\d*\.)?\d+$
    
    0 讨论(0)
  • 2020-12-06 11:34

    The following should work:

    ^(?!.*\..*\.)[.\d]+$
    

    This uses a negative lookahead to make sure that there are fewer than two . characters in the string.

    http://www.rubular.com/r/N3jl1ifJDX

    0 讨论(0)
提交回复
热议问题