Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex grouping confusion simple example

Tags:

java

regex

New to regex in java =)

I want to see as output:

aaaa
 222212
adasas

what I really see is:

aaaa 222212 adasas
aaaa
 222212

Code tells more then text, so here is my code:

String sToPars = "aaaa 222212 adasas";

Pattern p = Pattern.compile("(^[A-Za-z]+)( [0-9]+)( [A-Za-z]+)");

Matcher matcher = p.matcher(sToPars);
matcher.find();

for(int i = 0; i < matcher.groupCount();i++){
    System.out.println(matcher.group(i));
}

http://docs.oracle.com/javase/tutorial/essential/regex/groups.html What am I missing here..

like image 515
Mihkel L. Avatar asked Feb 23 '26 09:02

Mihkel L.


1 Answers

In the matcher object, the first group (index 0) is the complete match.

Afterwards, matcher's group of index 1 is the regex first capturing group's result, index 2 the second, etc...

To see what you want, you need to change your loop to:

for(int i = 1; i <= matcher.groupCount();i++)
like image 107
Robin Avatar answered Feb 24 '26 22:02

Robin