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

前端 未结 8 1964
孤街浪徒
孤街浪徒 2021-01-06 11:03

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 ne

8条回答
  •  梦毁少年i
    2021-01-06 11:40

    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.

提交回复
热议问题