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

前端 未结 8 1841
孤街浪徒
孤街浪徒 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-06 11:41

    try:

     If((str.indexOf("WARNING") > -1 || str.indexOf("ERROR") > -1) && str.indexOf("parsin") > -1)
    
    0 讨论(0)
  • 2021-01-06 11:42

    I usually use this applet to experiment with reg. ex. The expression may look like this:

    if (str.matches("(?i)^.*?(WARNING|ERROR).*?parsing.*$")) {
    ...
    

    But as stated in above answers it's better to not use reg. ex. here.

    0 讨论(0)
  • 2021-01-06 11:43

    If you've a variable number of words that you want to match I would do something like that:

    String mystring = "Text I want to match";
    String[] matchings = {"warning", "error", "parse", ....}
    int matches = 0;
    for (int i = 0; i < matchings.length(); i++) {
      if (mystring.contains(matchings[i]) {
        matches++;
      }
    }
    
    if (matches == matchings.length) {
       System.out.println("All Matches found");
    } else {
       System.out.println("Some word is not matching :(");
    }
    

    Note: I haven't compiled this code, so could contain typos.

    0 讨论(0)
  • 2021-01-06 11:43

    With multiple .* constucts the parser will invoke thousands of "back off and retry" trial matches.

    Never use .* at the beginning or in the middle of a RegEx pattern.

    0 讨论(0)
  • 2021-01-06 11:44

    Regular Expressions are not needed here. Try this:

    if((string1.toUpperCase().indexOf("ERROR",0) >= 0 ||  
      string1.toUpperCase().indexOf("WARNING",0) >= 0 ) &&
      string1.toUpperCase().indexOf("PARSING",0) >= 0 )
    

    This also takes care of the case-insensitive criteria

    0 讨论(0)
提交回复
热议问题