Skip to content

Java RegEx – OR Condition

Java RegEx – OR Condition example shows how to specify OR condition in Java regular expression pattern. The logical OR in regex is specified by the pipe (“|”) character.

How to specify an OR condition in the Java regex pattern?

Many times we want to find patterns that may have alternate forms. For example, we could be looking for either the word dog or cat in a string content. This can be achieved using the logical OR condition in Java regular expression.

The pipe (“|”) character is used to specify the OR condition in the regex pattern. For example, if you are looking for a character ‘a’, ‘b’, or ‘c’, then you can write an OR condition in the pattern like given below.

The above pattern means ‘a’, ‘b’, OR ‘c’. Now consider below-given example pattern that uses the OR condition.

It means ‘c’, ‘b’, OR ‘c’ as the first character that is followed by characters ‘a’ and ‘t’. This pattern will match with all three words “cat”, “bat”, and “fat”.

Let’s move on to a somewhat difficult pattern as compared to the above one. Suppose you want to validate a number that should be between 1 and 35 (both inclusive). For this, you can write a pattern using the logical OR condition like below.


Let’s test this pattern against some numbers.


As you can see from the output, our pattern worked perfectly for the numbers between 1 and 35. It did not match with the numbers below 1 and above 35 as per our pattern having OR conditions.

If you want to learn more about the regular expressions, you can visit the full Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author


Leave a Reply

Your email address will not be published.