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)
{
Matc开发者_Python百科her m = p.matcher(str);
if(m.matches())
System.out.println(str);
}
But it still not matches "K_CCC". Thanks
I wouldn't use RegEx for everything.
for(String str : ar)
{
if(!str.toUpperCase().startsWith("KB"))
System.out.println(str);
}
From the way your question is worded, I'm not entirely sure whether you want the match to be case insensitive or not. This regex:
(?i)[^k][^b].*
uses the flag (?i) to turn off case sensitivity, and should do want you want.
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);
}
A regex that matches anything not starting with KB is:
^(?!KB).*
To do it in java:
if (str.matches("^(?!KB).*$")) ...
You shouldn't use RegExes everywhere. Just create a simple check:
for (String str : ar)
{
if (!str.toLowerCase().startsWith("kb"))
System.out.println(str);
}
And I think, that this method is even better in performace (not that performance is needed in your case):
public static boolean accept(String name)
{
if (name.length() < 2) return true;
String sub = name.substring(0, 2);
return !sub.equalsIgnoreCase("KB");
}
What do others thing of this second way of working?
Use the regex (?i)^(?!kb).*
for case insensitive matches. It will avoid KB234 Kb*432, kB2343 and kb23445.
Here is the code snippet that can help for the ignore case understanding with String.matches function, for further details please use this [link][1]
String stringToSearch = "Four score and seven years ago our fathers ...";
// this won't work because the pattern is in upper-case
System.out.println("Try 1: " + stringToSearch.matches(".*SEVEN.*"));
// the magic (?i:X) syntax makes this search case-insensitive, so it returns true
System.out.println("Try 2: " + stringToSearch.matches("(?i:.*SEVEN.*)"));
Try 1: false Try 2: true
[1]: http://alvinalexander.com/blog/post/java/java-how-case-insensitive-search-string-matches-method/#:~:text=Solution%3A%20Use%20the%20String%20matches,must%20match%20the%20entire%20string.)
精彩评论