user1522820
user1522820

Reputation: 1604

Substitute a character literally in a regular expression in Java

I have a regular expression similar to this :-

abc{some dynamic character}abc

I want to substitute a character within braces at run-time. This dynamic character may be a special character (meta-characters, escape characters etc.).

How can I ensure that this dynamically formed regular expression is same as the one written by putting this character statically. (like "abc\\nabc")

Example :- Dynamic Character : '\n' Static Regular Expression : "abc\\nabc" Dynamic regex should be equal to static regex after replacing the character.

Upvotes: 2

Views: 162

Answers (1)

Garrett Hall
Garrett Hall

Reputation: 30032

You can use the Pattern class to escape your dynamic character:

"abc"  + Pattern.quote(dynamicCharacter) "abc"

Upvotes: 3

Related Questions