Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I provide an OR operator in regular expressions?

Tags:

java

regex

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.

like image 415
merveotesi Avatar asked Dec 04 '22 13:12

merveotesi


2 Answers

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 refiddle (this doesn't have Java specific checker), they make your life a lot easier!

like image 72
ppeterka Avatar answered Jan 12 '23 00:01

ppeterka


The "or" operator is spelled |, for example one|other.

All the operators are listed in the documentation.

like image 31
NPE Avatar answered Jan 12 '23 01:01

NPE