Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a Java String contains X or Y and contains Z

Tags:

java

string

regex

I'm pretty sure regular expressions are the way to go, but my head hurts whenever I try to work out the specific regular expression.

What regular expression do I need to find if a Java String (contains the text "ERROR" or the text "WARNING") AND (contains the text "parsing"), where all matches are case-insensitive?

EDIT: I've presented a specific case, but my problem is more general. There may be other clauses, but they all involve matching a specific word, ignoring case. There may be 1, 2, 3 or more clauses.

like image 409
Steve McLeod Avatar asked Nov 27 '22 19:11

Steve McLeod


2 Answers

If you're not 100% comfortable with regular expressions, don't try to use them for something like this. Just do this instead:

string s = test_string.toLowerCase();
if (s.contains("parsing") && (s.contains("error") || s.contains("warning")) {
    ....

because when you come back to your code in six months time you'll understand it at a glance.

Edit: Here's a regular expression to do it:

(?i)(?=.*parsing)(.*(error|warning).*)

but it's rather inefficient. For cases where you have an OR condition, a hybrid approach where you search for several simple regular expressions and combine the results programmatically with Java is usually best, both in terms of readability and efficiency.

like image 159
RichieHindle Avatar answered Dec 05 '22 10:12

RichieHindle


If you really want to use regular expressions, you can use the positive lookahead operator:

(?i)(?=.*?(?:ERROR|WARNING))(?=.*?parsing).*

Examples:

Pattern p = Pattern.compile("(?=.*?(?:ERROR|WARNING))(?=.*?parsing).*", Pattern.CASE_INSENSITIVE); // you can also use (?i) at the beginning
System.out.println(p.matcher("WARNING at line X doing parsing of Y").matches()); // true
System.out.println(p.matcher("An error at line X doing parsing of Y").matches()); // true
System.out.println(p.matcher("ERROR Hello parsing world").matches()); // true       
System.out.println(p.matcher("A problem at line X doing parsing of Y").matches()); // false
like image 23
João Silva Avatar answered Dec 05 '22 11:12

João Silva