【问题标题】:Java regex [a-z] matches digits and uppercase as wellJava regex [a-z] 也匹配数字和大写
【发布时间】:2016-02-26 00:36:18
【问题描述】:

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

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

结果不仅是“The end of sentence . Next sentence .”之类的内容,还有类似的内容:“Some numeric info 16 . 15 should not match this regex .”。

【问题讨论】:

  • 你能举一个完整的句子作为例子,并突出你想匹配和不想匹配的内容吗?如果我理解正确,您想要匹配所有点,但后面跟空格的点除外?
  • @Korgen 文本可能是这样的:“那只猫重 5.7 公斤。相当中等的猫。”我想匹配单词“kilos”附近的点。和“猫”。并使它们成为“公斤”和“猫”。我的正则表达式也适用于“5 . 7”。
  • @Antos 你的正则表达式工作正常——它在kilos 之后找到点。但是String#replace() 不知道您需要替换只替换那个特定的点,因此对文本中的所有 个点也是如此。
  • @SashaSalauyou 是的,好点。现在我正在尝试改变它。谢谢。

标签: java regex


【解决方案1】:

我建议为此使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多