[英]Replacing Pattern Matches in a String
String output = "";
pattern = Pattern.compile(">Part\s.");
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
match = matcher.group();
}
我正在嘗試使用上面的代碼查找>Part\\s.
模式>Part\\s.
在docToProcess
內部(這是一個大型xml文檔的字符串),然后我要做的是用<ref></ref>
替換與模式匹配的內容
有什么想法可以使output
變量等於docToProcess
除了上面指出的替換以外?
編輯:更換時我需要以某種方式使用匹配器。 我不能只使用replaceAll()
您可以使用String#replaceAll
方法。 它以Regex
作為第一個參數:-
String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");
請注意, dot (.)
是regex
的特殊元字符,它匹配所有內容,而不僅僅是dot(.)
。 因此,除非您確實想匹配>Part\\\\s
之后的任何字符,否則您需要對其進行轉義。 而且您需要添加2個反斜杠才能在Java中轉義。
如果要使用Matcher
類,則可以使用Matcher.appendReplacement方法:-
String docToProcess = "XYZ>Part .asdf";
Pattern p = Pattern.compile(">Part\\s\\.");
Matcher m = p.matcher(docToProcess);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "<ref></ref>");
}
m.appendTail(sb);
System.out.println(sb.toString());
輸出:-
"XYZ<ref></ref>asdf"
這是您需要的:
String docToProcess = "... your xml here ...";
Pattern pattern = Pattern.compile(">Part\\s.");
Matcher matcher = pattern.matcher(docToProcess);
StringBuffer output = new StringBuffer();
while (matcher.find()) matcher.appendReplacement(output, "<ref></ref>");
matcher.appendTail(output);
不幸的是,由於Java API的歷史限制,您不能使用StringBuilder
。
docToProcess.replaceAll(">Part\\s[.]", "<ref></ref>");
String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.