JavaGeek JavaGeek - 8 days ago 5
Java Question

Java regex case insensitivity not working

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


OUTPUT:

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

Answer

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"," "));
                                    ^^^^

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.

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