If I have a regular expression, how do I return the substring that it has found? I'm sure I must be missing something obvious, but I've found various methods to confirm that that substring is contained in the string I'm searching, or to replace it with something else, but not to return what I've found.
Matcher matcher = Pattern.compile("a+").matcher("bbbbaaaaabbbb");
if(matcher.find())
System.out.println(matcher.group(0)); //aaaaa
If you want specific parts
Matcher matcher = Pattern.compile("(a+)b*(c+)").matcher("bbbbaaaaabbbbccccbbb");
if(matcher.find()){
System.out.println(matcher.group(1)); //aaaaa
System.out.println(matcher.group(2)); //cccc
System.out.println(matcher.group(0)); //aaaaabbbbcccc
}
Group 0 is the complete pattern.. other groups are separated with parenthesis in the regex (
a+)
b*(
c+)
and can be get individually
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With