如果源字符串包含模式,则将其替换为某些内容或将其删除。一种方法是做这样的事情
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sourceString);
while(m.find()){
String subStr = m.group().replaceAll('something',""); // remove the pattern sequence
String strPart1 = sourceString.subString(0,m.start());
String strPart2 = sourceString.subString(m.start()+1);
String resultingStr = strPart1+subStr+strPart2;
p.matcher(...);
}
但是我想要这样的东西
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sourceString);
while(m.find()){
m.group.replaceAll(...);// change the group and it is source string is automatically updated
}
这可能吗?
谢谢
最佳答案
// change the group and it is source string is automatically updated
在 Java 中无法更改任何字符串,因此您所要求的是不可能的。
要删除或替换一个带有字符串的模式可以通过像
这样的调用来实现someString = someString.replaceAll(toReplace, replacement);
要转换匹配的子字符串,正如您的行所指示的那样
m.group().replaceAll("something","");
最好的解决方案可能是使用
- 结果的
StringBuffer
Matcher.appendReplacement
和Matcher.appendTail
。
例子:
String regex = "ipsum";
String sourceString = "lorem ipsum dolor sit";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sourceString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
// For example: transform match to upper case
String replacement = m.group().toUpperCase();
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
sourceString = sb.toString();
System.out.println(sourceString); // "lorem IPSUM dolor sit"
关于Java 正则表达式 : Replace part of source string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764515/