user1411335
user1411335

Reputation: 3600

Outputing Matched Capturing group in java

I am new to regular expressions and trying to process following regular expression to udentify ordinals in given text

((\\d*1)st|(\\d*2)nd|(\\d*3)rd|(\\d+)th)

I want to capture only the number part of the text for parsing ie. if the text is 21st then i want to capture 21 to be parsed into Integer . I know how to match on the regular expression to understand if the pattern exists and get the specific group. Is there any way I can get group that matched as output from the expression to extract the value ?

Thanks in advance

Upvotes: 2

Views: 73

Answers (2)

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

You can rewrite your regexp to use non-capturing groups like this:

(?:(\\d*)(?:st|nd|rd|th))

Upvotes: 1

Ina
Ina

Reputation: 4470

I've simplified your regex, and - importantly - I've added wildcards at each side. The first wildcard has ? to prevent greedy matching getting rid of the first digit of e.g. 21st.

The Pattern/Matcher approach lets you extract groups.

Pattern p = Pattern.compile(".*?(\\d*(1st|2nd|3rd|th)).*");
String input = "21st March 2013";
Matcher m = p.matcher(input);
if(m.matches())
    System.out.println(m.group(1));

Upvotes: 0

Related Questions