我有这样的输入
word w'ord wo'rd
我需要将单词开头和紧随其后的两个字符转换为大写'
字符(可以存在多次)。
我需要的输出(使用前面的示例)是
word W'Ord Wo'Rd
我尝试了一个简单的模式
s.replaceAll("(\\w)(\\w*)'(\\w)", "$1");
但我无法将组 1 和组 3 转换为大写
编辑:
在我发现主要问题中的一个小错误后,我编辑了 @Wiktor Stribizew 代码以包含我错过的案例。
Matcher m = Pattern.compile("(\\w)(\\w*)'(\\w)").matcher(s);
StringBuffer result = new StringBuffer();
while (m.find()) {
m.appendReplacement(result, m.group(1).toUpperCase() + m.group(2) + "'" + m.group(3).toUpperCase());
}
m.appendTail(result);
s = result.toString();
你需要使用Matcher#appendReplacement
在Java中能够处理匹配。这是一个例子:
String s = "word w'ord wo'rd";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("\\b(\\w)(\\w*)'(\\w(?:'\\w)*)").matcher(s);
while (m.find()) {
m.appendReplacement(result,
m.group(1).toUpperCase()+m.group(2) + "'" + m.group(3).toUpperCase());
}
m.appendTail(result);
System.out.println(result.toString());
// => word W'Ord Wo'Rd
See the Java演示
Java 9+ 等效项(demo):
String s = "wo'rd w'ord wo'r'd";
Matcher m = Pattern.compile("\\b(\\w)(\\w*)'(\\w(?:'\\w)*)").matcher(s);
System.out.println(
m.replaceAll(r -> r.group(1).toUpperCase()+r.group(2) + "'" + r.group(3).toUpperCase())
);
//wo'rd w'ord wo'r'd => Wo'Rd W'Ord Wo'R'D
//word w'ord wo'rd => word W'Ord Wo'Rd
模式分解:
-
\b
- 前导词边界
-
(\w)
- 第 1 组:单个单词字符
-
(\w*)
- 第 2 组:零个或多个单词字符
-
'
- 单引号
-
(\w(?:'\w)*)
- Group 3:
-
\w
- 一个单词字符
-
(?:'\w)*
- zero or more sequences of:
现在,如果您想让图案更精确,您可以更改\w
应该与小写字母匹配\p{Ll}
和\w
应该与任何字母匹配\p{L}
。图案看起来像"(?U)\\b(\\p{Ll})(\\p{L}*)'(\\p{Ll}(?:'\\p{Ll})*)"
- 但是,您可能会留下小写字母(之后的字母)'
)如果小写字母之前有大写字母(例如wo'r'D's
-> Wo'R'D's
). (?U)
is a Pattern.UNICODE_CHARACTER_CLASS
内联修饰符使得\b
字边界 Unicode 感知。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)