0

I have a string :

Patient:
${ss.patient.howard.firstName} ${ss.patient.howard.lastName}
Gender: ${ss.patient.howard.sex}
Birthdate: ${ss.patient.howard.dob}
${ss.patient.howard.addressLine1}
Phone: (801)546-4765

and I am trying to replace ${..} substrings with other strings so it would look like:

Patient:
firstName lastName

Gender:sex
Birthdate: dob
addressLine1
Phone: (801)546-4765
anubhava
  • 761,203
  • 64
  • 569
  • 643
sophist_pt
  • 329
  • 1
  • 8
  • 19
  • I am trying examleString.replaceFirst("\\${(.*?)\\}", (String) TestcaseContext.getCache().get(matcher.group(1))) and getting, Illegal repetition near index 1 \${(.*?)\} – sophist_pt Mar 30 '16 at 19:26
  • may be [This](http://stackoverflow.com/questions/10664434/escaping-special-characters-in-java-regular-expressions) will guide you in right direction? – cdp Mar 30 '16 at 19:30
  • Must you use regular expressions? I would consider the [Apache Commons Lang StrSubstitutor](https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html) for this particular application. It does exactly what you want. – KevinO Mar 30 '16 at 19:31

2 Answers2

2

You can use this regex with a capturing group:

String myString = "Patient:\n${ss.patient.howard.firstName} ${ss.patient.howard.lastName}\nGender: ${ss.patient.howard.sex}\nBirthdate: ${ss.patient.howard.dob}\n${ss.patient.howard.addressLine1}\nPhone: (801)546-4765";
myString = myString.replaceAll("\\$\\{[^}]+?\\.([^.}]+)}", "$1");

System.err.println(myString);

([^.}]+) is the capturing group before } and after the last DOT.

RegEx Demo

Output:

Patient:
firstName lastName
Gender: sex
Birthdate: dob
addressLine1
Phone: (801)546-4765
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You could try searching for ${string.string.string OR } and replace with empty string or nothing like this.

Regex: \${[a-z]+\.[a-z]+\.[a-z]+\.|}

Replacement to do: Replace with nothing or empty string.

Regex101 Demo