Java正则表达式不区分大小写不起作用 [英] Java regex case insensitivity not working
问题描述
我正在尝试使用正则表达式使用以下程序删除字符串中的某些单词.它可以正确删除,但只考虑大小写.如何使其不区分大小写.我将(?1)
保留在 replaceAll
方法中,但是没有用.
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 replaceAll
method but it didn't work.
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.
推荐答案
您需要将(?i)
放在想要的模式部分之前不区分大小写:
You need to place the (?i)
before the part of the pattern that you want to make case insensitive:
System.out.print(sample.replaceAll("(?i)\\b(?:is|the|in|any)\\b"," "));
^^^^
我用单词边界( \\ b
)替换了要删除的关键字周围的空格.之所以会出现问题,是因为可能有两个关键字一个接一个地被一个空格隔开.
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.
如果仅当关键字被空格包围时才想删除关键字,则可以使用正向前行和后向:
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)(?= )
这篇关于Java正则表达式不区分大小写不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!