让我们考虑以下示例:
String s = str.replaceAll("regexp", "$1");
Run Code Online (Sandbox Code Playgroud)
有些语言让我们指定\U$1的地方$1,其将匹配用大写字母组.如何使用Java实现相同的目标?
我知道我们可以使用Pattern类并获取组并将其转换为大写,但这不是我想要的.我想改变$1完成工作的东西.
我也尝试过:
String s = str.replaceAll("regexp", "$1".toUpperCase());
Run Code Online (Sandbox Code Playgroud)
但它看起来"$1".toUpperCase()是,"$1"而不是匹配.我确认使用:
String s = str.replaceAll("regexp", method("$1"));
// method declared as method()
private static String method(String s) {
System.out.println(s); // prints "$1"
return s;
}
Run Code Online (Sandbox Code Playgroud)
甚至在Java中是否允许?
编辑:
String s = "abc";
System.out.println(s.replaceAll("(a)", "$1")); // should print "Abc"
Run Code Online (Sandbox Code Playgroud)
编辑可能的DUPE:
我不是在寻找的方式使用m.group(),是否有可能使用类似\U$1的地方$1有replaceAll()
从 Java 9 开始,我们可以提供Functionto Matcher#replaceAll(Function<MatchResult,\xe2\x80\x8bString> replacer). 它比这里的其他答案更简洁。例如:
Pattern.compile("regexp")\n .matcher(str)\n .replaceAll(mr -> mr.group().toUpperCase());\nRun Code Online (Sandbox Code Playgroud)\n\n我们可以完全自定义此行为,因为我们持有MatchResult:
Pattern.compile("regexp")\n .matcher(str)\n .replaceAll(mr -> {\n String.format("%s %s", \n mr.group(1).toUpperCase),\n mr.group(2).indent(4);\n });\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
244 次 |
| 最近记录: |