Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Treat RegEx operator as simple character in java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading