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

后端 未结 3 1138
暖寄归人
暖寄归人 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 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

提交回复
热议问题