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

Redundant Character and Number Expected errors with RegEx expression

I’m writing a script to get out all the instances of #{ text } from a string so I can make it dynamic.

How can I use the Regex expression #{(.*?)} without running into errors?

I know the regex works, but I can’t assign it to a String because of the characters.

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

Thanks

Regex

enter image description here

>Solution :

In regex, hash(#) doesn’t need escaping as it doesn’t hold any special value.

In Java, you only need to escape opening curly braces { hence the correct regex you need to write is, #\{.*?} and in Java you need to escape \ character as it itself is a escape character hence the correct declaration should be #\\{.*?}

Try out this Java code,

public static void main(String[] args) {
    String s = "Dear #{abc}, your balance is #{xyz}";
    String regex = "#\\{.*?}";
    System.out.println("Before: " + s);
    s = s.replaceAll(regex, "test");
    System.out.println("After: " + s);
}

Which prints following as desired,

Before: Dear #{abc}, your balance is #{xyz}
After: Dear test, your balance is test

Also, for grabbing any character non-exhaustively, you can write [^}]* instead of .*? as former will perform better.

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