Extract two numbers from a string

I have a line such as the following:

"some value is 25, but should not be greater than 12"

I want to extract two numbers from a string.

Numbers are integers.

There can be no text before the first number and some text after the second number.

I tried to do this with regex and groups, but failed:

public MessageParser(String message) {
    Pattern stringWith2Numbers = Pattern.compile(".*(\\d?).*(\\d?).*");
    Matcher matcher = stringWith2Numbers.matcher(message);
    if (!matcher.matches()) {
        couldParse = false;
        firstNumber = 0;
        secondNumber = 0;
    } else {
        final String firstNumberString = matcher.group(1);
        firstNumber = Integer.valueOf(firstNumberString);
        final String secondNumberString = matcher.group(2);
        secondNumber = Integer.valueOf(secondNumberString);

        couldParse = true;
    }
}

Any help is appreciated.

+3
source share
3 answers

".*" , , , , . , ".*" , . , "\\d?" , , , .

, , , :

Pattern stringWith2Numbers = Pattern.compile(".*?(\\d+).*?(\\d+).*?");

, , ?

Pattern stringWith2Numbers = Pattern.compile("(\\d+).*?(\\d+)");

.

: , . , , . " 123 - ", "12" "3", . , , , :

Pattern stringWith2Numbers = Pattern.compile("(\\d+)\\D+(\\d+)");

, matches() , ^ $; find() , , OP. , matches(), "" . ( .) , :

Pattern stringWith2Numbers = Pattern.compile("\\D*(\\d+)\\D+(\\d+)\\D*");

... , , jjnguy.

+3

:

Pattern stringWith2Numbers = Pattern.compile("\\D*(\\d+)\\D+(\\d+)\\D*");

\\d+, .

+8

, .*, .

"\\D*(\\d+)\\D+(\\d+)\\D*".

This should be read as: at least one digital digit followed by at least one character that is not a numeric digit, followed by at least one digit.

+2
source

Source: https://habr.com/ru/post/1722618/


All Articles