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.
1 |
a|b|c |
The above pattern means ‘a’, ‘b’, OR ‘c’. Now consider below-given example pattern that uses the OR condition.
1 |
(c|b|f)at |
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.
1 |
^[1-9]|1[0-9]|2[0-9]|3[0-5]$ |
Where,
1 2 3 4 5 6 7 8 9 |
^ - Start of the string [1-9] - Any digit from 1 to 9 (covers 1 to 9 number) | - OR 1[0-9] - Digit 1 followed by any digit between 0 to 9 (covers 10 to 19 numbers) | - OR 2[0-9] - Digit 2 followed by any digit between 0 to 9 (covers 20 to 29 numbers) | - OR 3[0-5] - Digit 3 followed by any digit between 0 to 5 (covers 30 to 35 numbers) $ - End of the String |
Let’s test this pattern against some numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javacodeexamples.regex; public class RegExORConditionExample { public static void main(String[] args) { String[] strNumbers = { "0", "36", "19", "40", "100", "1000", "10", "1", "35", "11", "22", "30" }; String strPattern = "^[1-9]|1[0-9]|2[0-9]|3[0-5]$"; for(String strNumber : strNumbers) { System.out.println(strNumber + " => " + strNumber.matches(strPattern)); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 |
0 => false 36 => false 19 => true 40 => false 100 => false 1000 => false 10 => true 1 => true 35 => true 11 => true 22 => true 30 => true |
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.
This was well written, thanks.