Home > database >  Treat RegEx operator as simple character in java
Treat RegEx operator as simple character in java

Time:10-19

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);

CodePudding user response:

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!)
  • Related