我有这个代码,我想知道,如果我只能替换Java正则表达式中的组(不是所有模式).码:
//...
Pattern p = Pattern.compile("(\\d).*(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
//Now I want replace group one ( (\\d) ) with number
//and group two (too (\\d) ) with 1, but I don't know how.
}
Run Code Online (Sandbox Code Playgroud) 有没有办法用修改后的捕获组内容替换正则表达式?
例:
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
Run Code Online (Sandbox Code Playgroud)
而且我想用$ 1替换所有出现次数乘以3.
编辑:
看起来,有些不对劲:(
如果我使用
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
它抛出IllegalStateException:找不到匹配项
但
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
工作正常,但我不能改变$ 1 :(
编辑:
现在,它的工作:)
如果我有一个捕获组的正则表达式,例如foo(_+f).如果我将其与字符串匹配,并希望替换所有匹配中的第一个捕获组,baz以便这样做
foo___f blah foo________f
Run Code Online (Sandbox Code Playgroud)
转换为:
foobaz blah foobaz
Run Code Online (Sandbox Code Playgroud)
使用标准库似乎没有任何简单的方法.如果我使用 Matcher.replaceAll(),这将替换整个模式的所有匹配并将字符串转换为
baz blah baz
Run Code Online (Sandbox Code Playgroud)
显然,我可以迭代匹配,存储每个捕获组的开始和结束索引,然后返回并替换它们,但有更简单的方法吗?
谢谢,唐