2016-03-30 53 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