在Java 8中使用此regex,我想在考虑以下限制的情况下用大写字母更新我的保留字:
- 只将空格或句首/句尾之间的保留字大写
- 如果它在括号或方括号中,如果它没有包含在单词中,也要更新它
- 不要更新单词内或连字符后的保留字
我的代码:
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]);
查看在线演示,输出:
ID report with report-id is in the URL but not in the identifier (ID)
"(?i)(?<![\w-])" + Pattern.quote(word) + "(?![\w-])"
部分创建一个类似(?i)(?<![-w])id(?![-w])
的正则表达式,该正则表达式以不区分大小写的方式匹配id
(由于(?i)
嵌入的标志选项(,其前面没有-
或任何单词字符,后面也没有-
或任何单词字母。