Java Regex – get text after regex match example shows how to get the text that follows after regex match in Java using the regex groups and positive lookahead expression.
How to get text after the regex match from a string?
Often times when we want to find text after a regex match, we also get back the text that is part of the match. Consider below given example where I want to find a number after text “files”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExGetTextAfterMatch { public static void main(String[] args) { String str = "Processed files 100 out of 140"; Pattern pattern = Pattern.compile("files \\d+"); Matcher matcher = pattern.matcher(str); if(matcher.find()) { System.out.println( matcher.group() ); } } } |
Output
1 |
files 100 |
As you can see from the output, instead of just “100”, what we got is “files 100”.
There are a couple of ways using which we can get the text that follows after the match. The first one is to use the regex groups. In this approach, we need to create a group using the parentheses. We can then extract the text inside the group by using the group
method that accepts a group number parameter.
1 2 3 4 5 6 |
Pattern pattern = Pattern.compile("files (\\d+)"); Matcher matcher = pattern.matcher(str); if(matcher.find()) { System.out.println( matcher.group(1) ); } |
Output
1 |
100 |
In the above-given code, I created a regex group around the number I want to extract. Since it is the first group in the regex, I fetched it using the group(1)
instead of the group()
method.
Another way of getting a text that follows a regex match is to use the positive lookbehind expression. It can be defined using the “(?<=Expression)”. The positive lookbehind expression is used when we want to find something that follows something else but we don’t want to include that something else in the match.
1 2 3 4 5 6 7 8 |
String str = "Processed files 100 out of 140"; Pattern pattern = Pattern.compile("(?<=files\\s)\\d+"); Matcher matcher = pattern.matcher(str); if(matcher.find()) { System.out.println( matcher.group() ); } |
Output
1 |
100 |
As you can see from the output, when we use the positive lookbehind expression, it does not get included in the match.
If you want to learn more about regular expressions, please visit the Java Regex tutorial.
Please let me know your views in the comments section below.