gpt4 book ai didi

java - 使用正则表达式更新保留字(有异常(exception))

转载 作者:行者123 更新时间:2023-12-05 05:52:49 26 4
gpt4 key购买 nike

在 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)

除了连字符后的那个,我已经处理了所有的异常,你有改进我的代码的想法吗?

最佳答案

你可以使用

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)(?<![\\w-])" + Pattern.quote(word) + "(?![\\w-])"部分创建一个 regex like (?i)(?<![-\w])id(?![-\w])匹配 id以不区分大小写的方式(由于 (?i) 嵌入标志选项)不以 - 开头或任何单词 char,并且后面没有 -或任何字符字符。

关于java - 使用正则表达式更新保留字(有异常(exception)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70035954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com