Arsen Alexanyan Arsen Alexanyan - 2 months ago 8
Java Question

Match strings with regular expression in ignore case

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

Answer

A regex that matches anything not starting with KB is:

^(?!KB).*

To do it in java:

if (str.matches("^(?!KB).*$")) ...
Comments