Fran b
Fran b

Reputation: 3036

Inverse match with java regex

My input strings are like this:

foo 12
12 foo 123
foo 12 foo 1234
f1o2o 12345
foo 12 123456
...

I need capture the last number: 12, 123, 1234, 12345, 123456 ... Every line is processed by separate:

Pattern p = Pattern.compile(".*([0-9]+)$");
Matcher m = p.matcher("foo 12 123456");
m.matches()

Output: 6

Is there any form to inverse the matching? or how should I change the pattern for recover the last number?

Upvotes: 1

Views: 4018

Answers (2)

Braj
Braj

Reputation: 46861

There is no need to group it simply check for digits followed by end of line.

\d+$

DEMO

sample code:

Pattern p = Pattern.compile("\\d+$",Pattern.MULTILINE);
Matcher m = p.matcher("foo 12 123456\n12 foo 123");
while (m.find()) {
    System.out.println(m.group());
}

output:

123456
123

Greedy looks for the matches as many times as possible, hence it capture digits as well and leave last digit for [0-9]+

Make it non-greedy as suggested by @Zack Newsham

DEMO


You can try with Positive Lookbehind as well.

(?<=\D)\d+$

DEMO

Upvotes: 1

Bohemian
Bohemian

Reputation: 425178

Change your greedy quantifier to a reluctant one and use a one-line approach:

String lastNum = str.replaceAll("^.*?(\\d+)\\D*$", "$1");

This extracts 123456 from foo 12 123456 etc

Upvotes: 1

Related Questions