【问题标题】:Update reserved words (with exceptions) using regular expressions使用正则表达式更新保留字(有例外)
【发布时间】: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-])")

标签: java regex string


【解决方案1】:

你可以使用

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("(?i)(?<![\\w-])" + Pattern.quote(word) + "(?![\\w-])", word.toUpperCase()));
System.out.println(result[0]); 

见online demo,输出:

ID report with report-id is in the URL but not in the identifier (ID)

"(?i)(?&lt;![\\w-])" + Pattern.quote(word) + "(?![\\w-])" 部分创建一个 regex like (?i)(?&lt;![-\w])id(?![-\w]) 以不区分大小写的方式匹配 id(由于 (?i) 嵌入标志选项),其前面没有 - 或任何单词 char , 后面不跟- 或任何字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多