Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the String found with a regular expression

Tags:

java

regex

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.

like image 897
DenverCoder8 Avatar asked Dec 27 '22 08:12

DenverCoder8


1 Answers

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

like image 143
Rogel Garcia Avatar answered Jan 13 '23 19:01

Rogel Garcia