Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular expression matching square brackets

Tags:

java

regex

I'm trying to do the following using regular expression (java replaceAll):

**Input:**
Test[Test1][Test2]Test3

**Output**
TestTest3

In short, i need to remove everything inside square brackets including square brackets.

I'm trying this, but it doesn't work:

\\[(.*?)\\]

Would you be able to help?

Thanks,
Sash

like image 392
Pruthvi Raj Nadimpalli Avatar asked Apr 06 '17 05:04

Pruthvi Raj Nadimpalli


People also ask

How do you match square brackets in regex?

[[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .

How do you escape a square bracket in regex Java?

The first backslash escapes the second one into the string, so that what regex sees is \] . Since regex just sees one backslash, it uses it to escape the square bracket. In regex, that will match a single closing square bracket. If you're trying to match a newline, for example though, you'd only use a single backslash.

What do square brackets in regex mean?

A string enclosed in square brackets matches any one character in the string. 1. For example, regular expression [abc] matches a , b , or c . Within bracket_expression, certain characters have special meanings, as follows: 2.

What is \\ s+ in regex Java?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.


2 Answers

You can try this regex:

\[[^\[]*\]

and replace by empty

Demo

Sample Java Source:

final String regex = "\\[[^\\[]*\\]";
final String string = "Test[Test1][Test2]Test3\n";
final String subst = "";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
like image 177
Rizwan M.Tuman Avatar answered Sep 30 '22 14:09

Rizwan M.Tuman


Your original pattern works for me:

String input = "Test[Test1][Test2]Test3";
input = input.replaceAll("\\[.*?\\]", "");
System.out.println(input);

Output:

TestTest3

Note that you don't need the parentheses inside the brackets. You would use that if you planned to capture the contents in between each pair of brackets, which in your case you don't need. It isn't wrong to have them in there, just not necessary.

Demo here:

Rextester

like image 24
Tim Biegeleisen Avatar answered Sep 30 '22 15:09

Tim Biegeleisen