Java正则表达式不区分大小写无法正常工作

10
我正在尝试使用正则表达式从字符串中删除一些单词,使用以下程序进行操作。它可以正确地删除,但只能区分大小写。如何使它不区分大小写?我在replaceAll方法中添加了(?1),但没有起作用。
package com.test.java;

public class RemoveWords {

    public static void main(String args[])
    {

        // assign some words to string

        String sample ="what Is the latest news today in Europe? is there any thing special or everything is common.";

            System.out.print(sample.replaceAll("( is | the |in | any )(?i)"," "));
    }
}

输出:

what Is latest news today  Europe? there thing special or everything common.
3个回答

33

你需要在正则表达式的要进行大小写不敏感匹配的部分之前添加(?i)

System.out.print(sample.replaceAll("(?i)\\b(?:is|the|in|any)\\b"," "));
                                    ^^^^

查看它

我已经用单词边界(\\b)替换了要删除的关键字周围的空格。问题在于可能会有两个关键字紧挨着,只用一个空格分隔。

如果你只想在关键字被空格包围时才删除它们,那么你可以使用正向先行断言和后行断言:

(?i)(?<= )(is|the|in|any)(?= )

看一下


“the” 存在于输出中。它没有被替换为 “ ”,也没有删除 “IS”。请查看 http://www.ideone.com/HMxLr - user467871
正确。为什么它没有用空格替换“the”。正则表达式有问题吗? - JavaGeek
@codaddict:请注意,这会留下多个连续的空格,这可能不是理想的情况,但可能很难避免。 - Jon Skeet
@codaddict:是的...我认为这个问题够棘手,所以我删除了我的答案,决定让你来回答 :) - Jon Skeet
@codaddict 它完美地运作了。你能更详细地解释一下 (?<= ) 和 (?= ) 吗? - JavaGeek
显示剩余3条评论

4

我认为在快速替换中不能指定不区分大小写。可以尝试使用模式匹配。例如:

package com.test.java;

public class RemoveWords {

public static void main(String args[]) {
  // assaign some words to string
  String sample ="what Is the latest news today in Europe? is there any thing special or everything is common.";
  String regex = "( is | the |in | any )"
  System.out.print
  (
    Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(sample).replaceAll("")
  );
 }
}

1
抱歉给你点了踩,但是正如@codaddicts的回答所示,你可以String.replaceAll()中使用那些标志。 - Joachim Sauer
@Joachim:不用担心。我已经点赞了@Codaddicts的答案,因为我知道如何在String.replaceAll中使用标志。 - Chandu

1

is替换为[iI][sS]

sample.replaceAll("( [iI][sS] ...

它能够工作,但是这个过程很冗长,我们需要逐个输入每个字符。有没有更好的方法? - JavaGeek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接