Java RegEx:替换源字符串的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7764515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java RegEx: Replace part of source string
提问by Ali
If the source string contains the pattern, then replace it with something or remove it. One way to do it is to do something like this
如果源字符串包含模式,则将其替换为某些内容或将其删除。一种方法是做这样的事情
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(...);
}
But I want something like this
但我想要这样的东西
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
}
Is this possible?
这可能吗?
Thanks
谢谢
回答by aioobe
// change the group and it is source string is automatically updated
// change the group and it is source string is automatically updated
There is no way what so ever to change any string in Java, so what you're asking for is impossible.
没有办法改变Java中的任何字符串,所以你要求的是不可能的。
To removeor replacea pattern with a string can be achieved with a call like
可以通过如下调用来删除或替换字符串模式
someString = someString.replaceAll(toReplace, replacement);
To transformthe matched substring, as seems to be indicated by your line
要变换匹配的子字符串,如似乎是由您的线路指示
m.group().replaceAll("something","");
the best solution is probably to use
最好的解决方案可能是使用
- A
StringBuffer
for the result Matcher.appendReplacement
andMatcher.appendTail
.
- A
StringBuffer
为结果 Matcher.appendReplacement
和Matcher.appendTail
。
Example:
例子:
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"
回答by Thomas
Assuming you want to replace all occurences of a certain pattern, try this:
假设您要替换某个模式的所有出现,请尝试以下操作:
String source = "aabbaabbaabbaa";
String result = source.replaceAll("aa", "xx"); //results in xxbbxxbbxxbbxx
Removing the pattern would then be:
删除模式将是:
String result = source.replaceAll("aa", ""); //results in bbbbbb