June 18, 2012

Get the string that matches the regex

If you want to get the string that matches the regex pattern you have defined, you might have noticed there isn't any direct method. As a solution a simple code as below can be used.

I wanted to read the number within the brackets in str.
(Note: The numbers always appear within brackets)
String str = "CLor (23)";
String search = "\\(\\d*\\)";
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(str);
boolean matchFound = matcher.find();
if (matchFound) {
   int start = matcher.start();
   int end = matcher.end();
   String num = str.substring(start + 1, end - 1);
   System.out.println(num);
}

Above, in substring method I used
(start + 1, end -1)
because I needed to omit the brackets. If the whole string that matches the regex was needed method needs to have parameters
(start,end)

No comments:

Post a Comment