Java RegEx – Extract String Between Brackets

Java RegEx – Extract string between brackets example shows how to extract string data between brackets (square bracket or round bracket – parentheses) using Java regular expression pattern.

How to extract string data between brackets using regex?

Suppose you want to extract the number “105” from the text “Total files found: [105] out of 200”. That number is between two square brackets.

Since the square brackets are used to define a character class in the regular expressions, we need to escape brackets using double backslash characters to match it literally. Plus, since we want to extract a number between the opening and closing bracket, we are going to use the “\\d” in the pattern as given below.

Here the “\\d+” means one or more digits. Let’s try this pattern in the code.

Output

As you can see from the output, our code extracted the number between square brackets, but it included the brackets as well. In order to get just the number, we need to define a regex group, so that we can extract just that group in our code as given below.

Output

In the above example, we wanted to extract a number so we used the pattern “\\d”. But instead of a number, if you want to extract other text data, you can extract any text between the brackets using the “\\[(.*)\\]” pattern including numbers. See below given example.

Output

That worked as well. But wait, what about the string “Total files found: [105] out of [200]”? Now the string content has two square brackets. Let’s try that with the same regex pattern.

Output

Strange, right? Actually no, the “.*” is greedy in nature. It means it consumes all the text till the last instance of the ending square bracket “]”. So instead of a greedy expression i.e. “.*”, we need to use a reluctant expression i.e. “.*?” as given below.

Output

How to extract string between Round bracket or parentesis?

It can be done in the same way. Just like the square bracket, we also need to escape the round brackets. Everything else remains same as given below.

Output

If you want to learn more about the regex pattern, 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 *