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
[[\]] 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): [][] .
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.
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.
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.
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);
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With