[英]How to find and replace a substring?
例如,我有一个这样的字符串,其中我必须找到并替换多个子字符串,所有这些子字符串均以#
开头,包含6个符号,以'
结尾,并且不应包含)
...您认为最好的方式是实现吗?
谢谢!
编辑:我忘记的另一件事是进行替换,我需要该子字符串,即它被替换子字符串生成的字符串替换。
yourNewText=yourOldText.replaceAll("#[^)]{6}'", "");
或以编程方式:
Matcher matcher = Pattern.compile("#[^)]{6}'").matcher(yourOldText);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb,
// implement your custom logic here, matcher.group() is the found String
someReplacement(matcher.group());
}
matcher.appendTail(sb);
String yourNewString = sb. toString();
假设您只是知道子字符串的格式如您上面所解释的那样,但是不完全确定这6个字符的格式,请尝试以下操作:
String result = input.replaceAll("#[^\\)]{6}'", "replacement"); //pattern to replace is #+6 characters not being ) + '
这可能不是最好的方法,但是...
youstring = youstring.replace("#something'", "new stringx");
youstring = youstring.replace("#something2'", "new stringy");
youstring = youstring.replace("#something3'", "new stringz");
//阅读评论后编辑,谢谢
您必须使用带有正确正则表达式的replaceAll:
myString.replaceAll("#[^)]{6}'", "something")
如果您需要替换为匹配字符串的摘录,请使用一个匹配组,如下所示:
myString.replaceAll("#([^)]{6})'", "blah $1 blah")
第二个String中的$ 1与第一个String中的第一个括号表达式匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.