Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match strings with regular expression in ignore case

Tags:

java

regex

I need to match strings in my array which are not starting with "KB" string. I have tried this

String[] ar = {"KB_aaa","KB_BBB", "K_CCC", "!KBD", "kb_EEE", "FFFF"};
Pattern p = Pattern.compile("[^(^KB)].*");

for(String str : ar)
{
    Matcher m = p.matcher(str);
    if(m.matches())
         System.out.println(str);
}

But it still not matches "K_CCC". Thanks

like image 955
Arsen Alexanyan Avatar asked Oct 05 '11 11:10

Arsen Alexanyan


People also ask

How do you match a word with a case-insensitive in regex?

The i modifier is used to perform case-insensitive matching. For example, the regular expression /The/gi means: uppercase letter T , followed by lowercase character h , followed by character e . And at the end of regular expression the i flag tells the regular expression engine to ignore the case.

Which of the following regex function will result in ignoring case while matching pattern?

IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re. compile() .

Are regex matches case sensitive?

In Java, by default, the regular expression (regex) matching is case sensitive.


1 Answers

    String[] ar = {"KB_aaa","KB_BBB", "K_CCC", "!KBD", "kb_EEE", "FFFF"};
    Pattern p = Pattern.compile("^KB.*", Pattern.CASE_INSENSITIVE);

    for(String str : ar)
    {
        Matcher m = p.matcher(str);
        if(!m.matches())
             System.out.println(str);
    }
like image 175
palacsint Avatar answered Sep 21 '22 13:09

palacsint