Java正则表达式不敏感不起作用

Jav*_*eek 10 java regex

我正在尝试使用以下程序使用正则表达式删除字符串中的某些单词.它正确删除,但它只考虑区分大小写.如何使其不区分大小写.我保留(?1)replaceAll方法,但它没有用.

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)"," "));
    }
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

what Is latest news today  Europe? there thing special or everything common.
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 32

您需要将模式的一部分放在要使其不区分大小写的部分(?i) 之前:

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

看见

我已经使用word boundary(\\b)替换了要删除的关键字周围的空格.出现问题是因为可能有两个关键字一个接一个地被一个空格隔开.

如果您只想在空格包围的情况下删除关键字,那么您可以使用正向前瞻和后视:

(?i)(?<= )(is|the|in|any)(?= )
Run Code Online (Sandbox Code Playgroud)

看见