1
votes

I am using java Pattern Matcher api to search and replace tokens in a string. My string looks like below

Org Name: ${org_name}, Agent(s): ${agents}, OrgID: ${org_id}, ...

Here ${string} is the pattern I need to replace. I using regex like below

${(org_name|agents|org_id)}

But Pattern.compile is throwing exception. How to escape especial characters in this regex? or is there a better way of writing regex for this case?

1
Escape special regex metacharacters that you need to match literally and it will work. - Wiktor Stribiżew
So use \\$\\{(org_name|agents|org_id)\\} ... obey the @Wiktor - Tim Biegeleisen

1 Answers

3
votes

You need to escape the curly brackets ({ and }), which, in a regex pattern, imply quantifier; as well as the $ sign, which implies the end of line. Simply use backslashes: \:

\$\{(org_name|agents|org_id)\}

If it is not parsed as literal pattern, and rather as a string, you'll need to use \\:

\\$\\{(org_name|agents|org_id)\\}

Try:

\\$\\{(org_(id|name)|agents)\\}