我試圖取代XXYY1的XML標籤內的MessageParam ...Java的正則表達式替換XML標籤名
The MessageParam has requested to travel <BR/>From <MessageParam name="0" desc="city code"/> to <MessageParam name="1" desc="city code"/> on <MessageParam name="2" desc="date"/> at <MessageParam name="3" desc="time"/>.
我希望可以將輸出爲
The MessageParam has requested to travel <BR/>From <XXYY1 name="0" desc="city code"/> to <XXYY2 name="1" desc="city code"/> on <XXYY3 name="2" desc="date"/> at <XXYY4 name="3" desc="time"/>.
這裏是我的代碼
private void ProcessString()
{
String text = "The Traveler has requested to travel <BR/>From <MessageParam name=\"0\" desc=\"city code\"/> to <MessageParam name=\"1\" desc=\"city code\"/> on <MessageParam name=\"2\" desc=\"date\"/> at <MessageParam name=\"3\" desc=\"time\"/>.";
int Counter = 0;
StringBuffer outString = new StringBuffer();
Pattern pattern = Pattern.compile("(<MessageParam.*?>)");
Matcher matcher = pattern.matcher(text);
while (matcher.find())
{
Counter++;
String sReplacer = new StringBuffer("XXYY").append(Counter).toString();
matcher.appendReplacement(outString, sReplacer);
}
matcher.appendTail(outString);
System.out.println(outString.toString());
}
我得到的輸出是
The MessageParam has requested to travel <BR/> From XXYY1 to XXYY2 on XXYY3 at XXYY4.
我很確定我的正則表達式不正確。因爲我用正則表達式不好,我無法弄清楚什麼是錯誤的。
由於您不需要剩下的部分,您可以只搜索'
Alex
不要使用正則表達式解析非正則語言! –