tags:

views:

72

answers:

3

Hi guys,

I'm trying to get a regexp to solve the next problem:

I have some strings with the next format "somename 1 of 20 and something else" I want to retrieve the "1" from the string

I'm trying with

Pattern pat = Pattern.compile("(?<!of\\s)(\\d+)\\s", Pattern.CASE_INSENSITIVE);
Matcher matcher = pat.matcher(tmp);

But doesn't work as I was expecting.

The "somename" string can also contain numbers, so basically the logic should be "get the last number before 'of '"

Any tip?

Thanks.

+2  A: 

You mean you want to match "x of y"? Try this:

\\b(\\d+)\\s+of\\s+(\\d+)
soulmerge
Thanks a lot. That's exactly what I needed :)
Carlos Tasada
A: 

This seems to work for simple test cases, but there's probably some corner case(s) not covered:

Pattern pat = Pattern.compile(".* (\\d+) of \\d+.*", Pattern.CASE_INSENSITIVE);
String tmp = "somename 1 of 20 and something else";
Matcher matcher = pat.matcher(tmp);
if (matcher.matches()) {
    System.out.println(matcher.group(1));
}
pmac72
A: 

Your pattern works fine. One thing you need to remember is that you need to initialize the Matcher correctly. From the Matcher JavaDoc:

The explicit state of a matcher is initially undefined; attempting to query any part of it before a successful match will cause an IllegalStateException to be thrown. The explicit state of a matcher is recomputed by every match operation.

String tmp= "somename 1 of 20 and something else";
Pattern pat = Pattern.compile("(?<!of\\s)(\\d+)\\s");
Matcher matcher = pat.matcher(tmp);
System.out.print(matcher.find()); //matcher.find() will initialize state
System.out.println(":" + matcher.group(1));

will return:

true:1

akf