【发布时间】:2021-11-19 13:54:16
【问题描述】:
在 Java 8 中使用这个正则表达式,考虑到这些限制,我想用大写更新我的保留字:
- 仅将空格之间或句子开头/结尾的保留字大写
- 如果它在括号或方括号中,如果它不包含在单词中,也要更新它
- 不要更新包含在单词中或连字符后的保留字
我的代码:
String[] RESERVED_WORDS = { "id", "url" };
String[] result = {"id report with report-id is in the url but not in the identifier (id)"};
Arrays.stream(RESERVED_WORDS).forEach(word -> result[0] = result[0].replaceAll("(\\b" + word + "\\b", word.toUpperCase()));
我的结果:
ID report with report-ID is in the URL but not in the identifier (id)
我的期望:
ID report with report-id is in the URL but not in the identifier (ID)
除了连字符后的异常,我已经处理了所有异常,你知道改进我的代码吗?
【问题讨论】:
-
相关方法的文档说:“请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换时不同细绳;请参阅 Matcher.replaceAll。如果需要,使用 Matcher.quoteReplacement(java.lang.String) 来抑制这些字符的特殊含义。”您可能想从那里开始。
-
空白边界为
(?<!\S)/(?!\S)。你需要"(?<!\\S)" + word + "(?!\\S)"或"(?<!\\S)" + Pattern.quote(word) + "(?!\\S)" -
仅供参考:ideone.com/8HgTsS
-
@WiktorStribiżew 但是对于示例:“Base rate usd (usd)”不起作用,第二个美元没有改变,也需要改变,有什么想法可以解决吗?
-
(?<![-\w])id(?![-\w]),见regex101.com/r/u7ot3L/1和ideone.com/Ak7r9H ("(?<![\\w-])" + Pattern.quote(word) + "(?![\\w-])")