Anonymous
Anonymous

Reputation: 477

Python and Java regex behavior different when using the same regex

There are several questions about this but non answered my question. I wish to use pattern and matcher to find a pattern in a string and then from there create a list out of the matches that include the rest of the not match as well.

 String a = "125t160f"; // The "t" could be replaced with symbols such as "." or anything so I wish to take one of anything after many digits.
 Matcher m = Pattern.compile("(\\.?\\d+\\.)").matcher(a);
 System.out.println(m.find());

My current result:

False

My expected result should be in list:

["125t", "160f"] // I understand how to do it in python but not in java. So could anyone assist me in this.

Upvotes: 1

Views: 50

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522049

Your pattern should be \d+\D:

String a = "125t160f";
Matcher m = Pattern.compile("\\d+\\D").matcher(a);
while (m.find()) {
    System.out.println(m.group(0));
}

The above regex pattern says to match one or more digits, followed by a single non digit character. If we can't rely on a non digit character to know when to stop matching, then we would need to know how many digits to consume.

Upvotes: 1

Related Questions