Regex pattern for numbers with dots

前端 未结 4 934
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 08:58

I need a regex expression for this

any number then . and again number and .

So this is valid

1.3.164.1.2583.15.46
546.598.856.1.68.268.695.5         


        
相关标签:
4条回答
  • 2021-01-13 09:40

    You could match with the following regular expression.

    (?<![.\d])\d+(?:\.\d+)+(?![.\d])
    

    Start your engine!

    The negative lookarounds are to avoid matching .1.3.164.1 and 1.3.164.1.. Including \d in the lookarounds is to avoid matching 1.3.16 in 1.3.164.1..

    Java's regex engine performs the following operations.

    (?<![.\d])  : negative lookbehind asserts following character is not
                  preceded by a '.' or digit
    \d+         : match 1+ digits
    (?:\.\d+)   : match '.' then 1+ digits in a non-capture group
    +           : match the non-capture group 1+ times
    (?![.\d])   : negative lookahead asserts preceding character is not
                  followed by a '.' or digit
    
    0 讨论(0)
  • 2021-01-13 09:47

    I was thinking recursive regex here, and my pattern is:

    pattern = "\\d+.\\d+(?:.\\d+.\\d+)*"
    
    0 讨论(0)
  • 2021-01-13 09:48

    This one [0-9]+([.][0-9]+)* equivalent to \\d+([.]\\d+)* is valid for

    1.3.164.1.2583.15.46 , 546.598.856.1.68.268.695.5955565 and 5465988561682686955955565

    And this one [0-9]+([.][0-9]+)+ equivalent to \\d+([.]\\d+)+ is valid for

    1.3.164.1.2583.15.46 and 546.598.856.1.68.268.695.5955565 but not for 5465988561682686955955565

    0 讨论(0)
  • 2021-01-13 09:56

    Something like this should work:

    (\\d+\\.?)+

    Edit

    Yep, not clear from the description if a final . is allowed (assuming an initial one is not).

    If not:

    (\\d+\\.?)*\\d+ or \\d+(\\.\\d+)* (if that seems more logical)

    Test

    for (String test : asList("1.3.164.1.2583.15.46",
        "546.598.856.1.68.268.695.5955565", "5..........", "...56.5656"))
        System.out.println(test.matches("\\d+(\\.\\d+)*"));
    

    produces:

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