Regex to find integer or decimal from a string in java in a single group?

后端 未结 3 1137
暖寄归人
暖寄归人 2021-01-05 12:31

I am trying (\\d+|\\d+\\.\\d+) on this sample string:

Oats     124   0.99        V    1.65

but it is giving me decimal number

相关标签:
3条回答
  • 2021-01-05 12:47

    Question not entirely clear, but the first problem I see is . is a magic character in regex meaning any character. You need to escape it with as . There are lots of regex cheat sheets out there, for example JavaScript Regex Cheatsheet

    (\d+|\d+\.\d+)
    
    0 讨论(0)
  • 2021-01-05 12:50

    Try this pattern:

    \d+(?:\.\d+)?
    
    Edit:
    \d+ match 1 or more digit
    (?: non capturing group (optional)
       \. '.' character
       \d+ 1 or more digit
    )?  Close non capturing group 
    
    0 讨论(0)
  • 2021-01-05 13:03

    You don't need to have a separate patterns for integer and floating point numbers. Just make the decimal part as optional and you could get both type of numbers from a single group.

    (\d+(?:\.\d+)?)
    

    Use the above pattern and get the numbers from group index 1.

    DEMO

    Code:

    String s = "Oats     124   0.99        V    1.65";
    Pattern regex = Pattern.compile("(\\d+(?:\\.\\d+)?)");
     Matcher matcher = regex.matcher(s);
     while(matcher.find()){
            System.out.println(matcher.group(1));
    }
    

    Output:

    124
    0.99
    1.65
    

    Pattern explanation:

    • () capturing group .
    • \d+ matches one or more digits.
    • (?:) Non-capturing group.
    • (?:\.\d+)? Matches a dot and the following one or more digits. ? after the non-capturing group makes the whole non-capturing group as optional.

    OR

    Your regex will also work only if you change the order of the patterns.

    (\d+\.\d+|\d+)
    

    DEMO

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