java Java正则表达式不区分大小写不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4813497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:08:26  来源:igfitidea点击:

Java regex case insensitivity not working

javaregex

提问by JavaGeek

I'm trying to remove some words in a string using regex using below program. Its removing properly but its considering only case sensitive. How to make it as case insensitive. I kept (?1)in replaceAllmethod but it didn't work.

我正在尝试使用下面的程序使用正则表达式删除字符串中的一些单词。它正确删除,但只考虑区分大小写。如何使它不区分大小写。我保留(?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)"," "));
    }
}

OUTPUT:

输出:

what Is latest news today  Europe? there thing special or everything common.

回答by codaddict

You need to place the (?i)beforethe part of the pattern that you want to make case insensitive:

您需要将 放在要使大小写不敏感的模式部分(?i)之前

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

See it

看见

I've replaced spaces around the keywords to be removed with word boundary (\\b). The problem comes because there may be two keywords one after another separated by just one space.

我已经用词边界 ( \\b)替换了要删除的关键字周围的空格。问题来了,因为可能有两个关键字一个接一个地被一个空格隔开。

If you want to delete the keywords only if they are surrounded by space, then you can use positive lookahead and lookbehind as:

如果您只想删除被空格包围的关键字,那么您可以使用积极的前瞻和后视:

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

See it

看见

回答by Chandu

I don't think you can specify case insensitive with the quick replace. Try a pattern instead. i.e:

我认为您不能通过快速替换指定不区分大小写。尝试一种模式。IE:

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("")
  );
 }
}

回答by Chandu

change isto [iI][sS]

更改is[iI][sS]

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