0

I'm pretty new to java regexp and trying to compile a Pattern that simplifies this:

String str1;
String str2;
String str3;
String str4;
String str;

if ((str.contains(str1) || str.contains(str3)) &&
        str.contains(str3) || str.contains(str)) {
    return true;
} else {
    return false;
}

I figured out I can do the OR with "|" but how do I compile the AND?

I want to be able to compile the pattern and check many strings with good performance.

EDIT:

I got this now :

private static boolean checkPatternOR() {

    String patternString = "foo"  ;

    Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);

    Matcher matcher1 = pattern.matcher("foo bar");
    Matcher matcher2 = pattern.matcher("something else");


    System.out.println("does it match? " + (matcher1.lookingAt() && matcher2.lookingAt()));

    return true;

}

How would I merge matcher1 and matcher2 into one?

Ali
  • 56,466
  • 29
  • 168
  • 265
pinpox
  • 179
  • 2
  • 10

1 Answers1

0
// [] is how you match regex patterns by OR 
if(str.matches("[(*str1 here*)(*str2 here*)(*etc*)]")
    // best to separate AND into a separate regex
    && str.matches("regex here")) {
    // do whatever
}

If I've understood you correctly.

If not, then just encase your Java OR statements (||, ||, ||) in brackets:

if((str.contains(str1) || str.contains(str2) && (str.contains(str3)) {
    // do whatever
}
Gorbles
  • 1,169
  • 12
  • 27