javaregex

How can I provide an OR operator in regular expressions?


I want to match my string to one sequence or another, and it has to match at least one of them.

For and I learned it can be done with:

(?=one)(?=other)

Is there something like this for OR?

I am using Java, Matcher and Pattern classes.


Solution

  • Generally speaking about regexes, you definitely should begin your journey into Regex wonderland here: Regex tutorial

    What you currently need is the | (pipe character)

    To match the strings one OR other, use:

    (one|other)
    

    or if you don't want to store the matches, just simply

    one|other
    

    To be Java specific, this article is very good at explaining the subject

    You will have to use your patterns this way:

    //Pattern and Matcher
    Pattern compiledPattern = Pattern.compile(myPatternString);
    Matcher matcher = pattern.matcher(myStringToMatch);
    boolean isNextMatch = matcher.find(); //find next match, it exists, 
    if(isNextMatch) {
        String matchedString = myStrin.substring(matcher.start(),matcher.end());
    }
    

    Please note, there are much more possibilities regarding Matcher then what I displayed here...

    //String functions
    boolean didItMatch = myString.matches(myPatternString); //same as Pattern.matches();
    String allReplacedString = myString.replaceAll(myPatternString, replacement)
    String firstReplacedString = myString.replaceFirst(myPatternString, replacement)
    String[] splitParts = myString.split(myPatternString, howManyPartsAtMost);
    

    Also, I'd highly recommend using online regex checkers such as Regexplanet (Java) or regex101, they make your life a lot easier!