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