[英]How to replace multiple instances of substring within a string
I need to replace some of the contents of a large string with different content in the same spot. 我需要在同一个地方替换不同内容的大字符串的一些内容。
Lets say I have a string: 让我们说我有一个字符串:
String str = "package blah.foo.bar;\n"
+ "import org.blah.blah;\n"
+ "import sel.this.that;\n"
+ "import sel.boo.foo;\n"
+ "...more text";
I want to insert the word gen
into statements which start with import sel.
我想将单词
gen
插入以import sel.
开头的语句中import sel.
So that the end result looks like: import sel.gen.this.that;
所以最终结果如下:
import sel.gen.this.that;
I have had success with the following method but only when I KNOW where that substring will be within the string. 我已经成功使用以下方法,但只有当我知道子字符串在字符串中的位置时。 My issue is that I'm not sure how to make the following code dynamic:
我的问题是,我不确定如何使以下代码动态:
private String modifyString(String str){
String hold = str.substring(0, str.indexOf(";"));
hold = new StringBuilder(hold).insert(13, "gen.").toString();
str = str.replace("(?m)^package.*", hold);
return str;
}
The above code correctly replaces the strings package blah.foo.bar;
上面的代码正确地替换了字符串
package blah.foo.bar;
with package blah.gen.foo.bar;
与
package blah.gen.foo.bar;
But again this only works with replacing the beginning portion of the string. 但这又一次只能替换字符串的开头部分。 I'm looking to be able to hold all instances of a substring and then insert a substring within those substrings.
我希望能够保存子字符串的所有实例,然后在这些子字符串中插入子字符串。
You can use a simple line like: 你可以使用一个简单的行:
str = str.replaceAll("import sel\\.", "import sel.gen.");
replace
takes a literal string expression as an argument, not a regex. replace
将文字字符串表达式作为参数,而不是正则表达式。
This should work and is simpler than using a regex: 这应该工作,比使用正则表达式更简单:
String result = str.replace("import sel.", "import sel.gen.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.