-1

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.

Thanks

Regex

enter image description here

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

My end goal is to eventually just get all the tokens out and manipulate the sting builder separately so this is plenty okay for now thank you so much for the help. I didn't know about the #

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.