2016-03-30 11 views
0

私は、文字列があります。javaの正規表現パターンで特殊文字をエスケープするには?

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 

をし、私はそれは次のようになりますので、他の文字列と${..}部分文字列を置換しようとしています:

Patient: 
firstName lastName 

Gender:sex 
Birthdate: dob 
addressLine1 
Phone: (801)546-4765 
+0

私は "\\ $ {(*)\\。?}"(examleString.replaceFirstをしようとしています、(文字列)TestcaseContext.getCache()。 get(matcher.group(1)))と取得すると、インデックス1の近くで不正な繰り返しが発生する \ $ {(。*?)\} –

+0

は[This(http://stackoverflow.com/questions/10664434/escaping-特殊文字のjava正規表現)は正しい方向にあなたを導くでしょうか? – cdp

+0

正規表現を使用する必要がありますか?私はこの特定のために[Apache Commons Lang StrSubstitutor](https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html)を検討します応用。それはまさにあなたが望むものです。 – KevinO

答えて

2

あなたはキャプチャグループと、この正規表現を使用することができます。

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); 

([^.}]+)}前に、最後のドットの後のキャプチャグループです。

RegEx Demo

出力:

Patient: 
firstName lastName 
Gender: sex 
Birthdate: dob 
addressLine1 
Phone: (801)546-4765 
+1

ありがとう@anubhava、キャプチャグループについて知っておきたいこと。それはトリックでした。 –

0

あなたは${string.string.string OR }を検索してみてくださいとemptyで置き換えることができます文字列またはこれのようなnothing

正規表現:行うには\${[a-z]+\.[a-z]+\.[a-z]+\.|}

交換:何か空の文字列で置き換えます。

Regex101 Demo

関連する問題