Ok so I have a String which looks something like this
[RandomChars] Name
and I want to remove the
[RandomChars]
part of the String.
The problem I run in to is that regex treats the [ and ] as operators and not as characters.
I thought adding \\ before the operators would make them act as characters but that doesn’t seem to work.
Here is some sample code
String strOriginal = "[TAS] ElDuko";
String changed = strOriginal.replaceAll("\\[\\D\\]", "");
System.out.println(changed);
>Solution :
You can use
String changed = strOriginal.replaceAll("\\s*\\[[^\\]\\[]*]", "").trim();
See the regex demo and mind the .trim() at the end.
Details:
\s*– zero or more whitespaces\[– a[char[^\]\[]*– zero or more chars other than[and]]– a]char (it is not special!)