我想检查模式匹配,如果模式匹配,那么我想将这些文本匹配替换为测试数组中给定索引处的元素。
public class test {
public static void main(String[] args) {
String[] test={"one","two","three","four"}
Pattern pattern = Pattern.compile("\\$(\\d)+");
String text="{\"test1\":\"$1\",\"test2\":\"$5\",\"test3\":\"$3\",\"test4\":\"$4\"}";
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println(matcher.groupCount());
System.out.println(matcher.replaceAll("test"));
}
System.out.println(text);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望最终结果文本字符串采用以下格式:
{\"test1\":\"one\",\"test2\":\"$two\",\"test3\":\"three\",\"test4\":\"four\"}
Run Code Online (Sandbox Code Playgroud)
但 while 循环在一场比赛后退出,并"test"在各处被替换,如下所示:
{"test1":"test","test2":"test","test3":"test","test4":"test"}
Run Code Online (Sandbox Code Playgroud)
使用下面的代码我得到了结果:
public class test {
public static void main(String[] args) {
String[] test={"one","two","three","four"};
Pattern pattern = Pattern.compile("\\$(\\d)+");
String text="{\"test1\":\"$1\",\"test2\":\"$2\",\"test3\":\"$3\",\"test4\":\"$4\"}";
Matcher m = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, test[Integer.parseInt(m.group(1)) - 1]);
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个像这样的替换文本数组,
String[] test={"$$one","two","three","four"};
Run Code Online (Sandbox Code Playgroud)
然后,由于$$,我在线程“main”中遇到异常:
java.lang.IllegalArgumentException:java.util.regex.Matcher.appendReplacement(Matcher.java:857)处的非法组引用**
以下行是您的问题:
System.out.println(matcher.replaceAll("test"));
Run Code Online (Sandbox Code Playgroud)
如果删除它,循环将遍历所有匹配项。
作为问题的解决方案,您可以将循环替换为如下所示:
对于 Java 8:
StringBuffer out = new StringBuffer();
while (matcher.find()) {
String r = test[Integer.parseInt(matcher.group(1)) - 1];
matcher.appendReplacement(out, r);
}
matcher.appendTail(out);
System.out.println(out.toString());
Run Code Online (Sandbox Code Playgroud)
对于 Java 9 及更高版本:
String x = matcher.replaceAll(match -> test[Integer.parseInt(match.group(1)) - 1]);
System.out.println(x);
Run Code Online (Sandbox Code Playgroud)
$5只有当您用$2我认为是您的目标的替换 时,这才有效。
关于$替换字符串中的符号,文档指出:
美元符号 ($) 可以作为文字包含在替换字符串中,方法是在其前面加上反斜杠 (\$)。
换句话说,您必须将替换数组编写为String[] test = { "\\$\\$one", "two", "three", "four" };
| 归档时间: |
|
| 查看次数: |
2452 次 |
| 最近记录: |