gpt4 book ai didi

Java 正则表达式 [a-z] 也匹配数字和大写字母

转载 作者:太空宇宙 更新时间:2023-11-04 12:53:10 25 4
gpt4 key购买 nike

我有大量文字。目标是用空格分隔点,这些点仅出现在句子的末尾,而不出现在缩写、时间、日期或其他内容中。这样做:

    String regex = "[a-z](\\.)\\s";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if(matcher.find())
text = text.replace(matcher.group(1), " " + matcher.group(1));

结果不仅是“句子结尾。下一个句子。”,还有这样的内容:“某些数字信息 16 . 15 不应与此正则表达式匹配。”。

最佳答案

我建议使用 Matcher#replaceAll() 为此:

Pattern regex = Pattern.compile("([a-z])\\.(\\s|$)");
text = regex.matcher(text).replaceAll("$1 .$2"); // $1 is for letter, $2 is for space/end of line

使用lookbehind(?<=)实现同样的效果:

Pattern regex = Pattern.compile("(?<=[a-z])\\.(\\s|$)");
text = regex.matcher(text).replaceAll(" .$1"); // $1 now is for space/end of line

关于Java 正则表达式 [a-z] 也匹配数字和大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631887/

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