[英]Custom Regex Replacement in Java
我想在字符串中找到與正則表達式匹配的所有模式:no =“(\\ d +)”然后用其他東西替換組中的數字。
在下面的方法中,我可以找到並替換整個匹配,但這不是我想要的。 有沒有辦法只替換那場比賽的一部分?
private String replaceStringFromPatternSearch(String stringToSearch, String patternString, String replacementString) {
String replacedString = null;
Pattern stringPattern = Pattern.compile(patternString);
Matcher stringMatcher = stringPattern.matcher(stringToSearch);
replacedString = stringMatcher.replaceAll(replacementString);
if (replacedString != null) {
return replacedString;
} else {
return stringToSearch;
}
}
選項1:在替換功能中使用捕獲緩沖區
在replaceAll
,您可以從諸如捕獲的文本和當時要插入的字符串等組件構建替換。 這是一個例子:
String replaced = yourString.replaceAll("no=\"(\\d+)\"",
"Something $1 Something else");
在替換中, $1
是捕獲的數字。 您不必使用它們,但正如您所看到的,您可以圍繞它們構建替換字符串。
選項2(替換Lambda / Callback / Delegate Equivalent):一次構建一個匹配
在Java中,為了構建更復雜的替換,我們沒有替換lambdas,但我們可以這樣做:
StringBuffer resultString = new StringBuffer();
Pattern regex = Pattern.compile("no=\"(\\d+)\"");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// You can vary the replacement text for each match on-the-fly
// String computed_replacement = .... Something wild!
regexMatcher.appendReplacement(resultString, computed_replacement );
}
regexMatcher.appendTail(resultString);
這兩種方法都解決了我的問題:
示例數據:<detail type =“07”time =“100611”no =“07040365089”detail“>
我認為我想用其他東西替換07040365089。 no =“\\ d”在實際數據中多次出現。 不同模式還需要其他替換。
private String replaceStringFromPatternSearch2(String stringToSearch, String patternString, String replacementString) {
String replacedString = "";
Pattern stringPattern = Pattern.compile(patternString);
int startSearch = 0;
Matcher stringMatcher = stringPattern.matcher(stringToSearch);
while (stringMatcher.find(startSearch)) {
int start = stringMatcher.start(1);
int end = stringMatcher.end(1);
replacedString += stringToSearch.substring(startSearch, start) + replacementString + stringToSearch.substring(end);
startSearch = end + 1;
}
if (!replacedString.isEmpty()) {
return replacedString;
} else {
return stringToSearch;
}
}
private String replaceStringFromPatternSearch(String stringToSearch, String patternString, String replacementString) {
String replacedString = "";
Pattern stringPattern = Pattern.compile(patternString);
int startSearch = 0;
Matcher stringMatcher = stringPattern.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while (stringMatcher.find()) {
String wholeGroup = stringMatcher.group(0);
replacedString = wholeGroup.replace(stringMatcher.group(1), replacementString);
stringMatcher.appendReplacement(sb, replacedString);
}
stringMatcher.appendTail(sb);
if (sb.length() > 0) {
return sb.toString();
} else {
return stringToSearch;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.