Java RegEx – Get Text After Regex Match

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”.

Output

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.

Output

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.

Output

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.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *