我知道有两种方法可以替换字符串中所有出现的子字符串.
正则表达式方式(假设"要替换的子字符串"不包括正则表达式特殊字符):
String regex = "substring-to-be-replaced" + "+";
Pattern scriptPattern = Pattern.compile(regex);
Matcher matcher = scriptPattern.matcher(originalstring);
newstring = matcher.replaceAll("replacement-substring");
Run Code Online (Sandbox Code Playgroud)
String.replace()方式:
newstring = originalstring.replace("substring-to-be-replaced", "replacement-substring");
Run Code Online (Sandbox Code Playgroud)
哪两个更有效(以及为什么)?
有没有比上述两种更有效的方法?
我有一串以下格式
Select * where {{0} rdfs:label "Aruba" } limit 10
Run Code Online (Sandbox Code Playgroud)
现在我想用一些新文本替换{0},但问题是消息格式由于第一个大括号而无法解析字符串.我知道如果我使用'{'它会逃避它,但问题是我有大量这种类型的字符串,我不能手动添加大括号之前和之后的单引号.即使我编写了一个函数来执行此操作,它也会转义占位符{0}的大括号.
它们是消息格式的更好替代品,例如ruby字符串插值.我只想要一种方法来编写一个字符串模板,我可以用新的字符串替换某些部分