Reputation: 955
I want to test using java regex the following cases:
Here are the A, B and C regex:
(([0-9]{1,3})(\.[0-9]{1,3})?)
(\+([0-1](\.[0-9]{1,3}))
(-([0-1](\.[0-9]{1,3}))
So how can I create my regex using a logical OR?
Solution
^(([0-9]{1,3})(\.[0-9]{1,3})?)([-+]([0-1](\.[0-9]{1,3}))|(\+([0-1](\.[0-9]{1,3}))(\-([0-1](\.[0-9]{1,3})))))$
Upvotes: 2
Views: 147
Reputation: 107287
You can combine the B
and C
regexes with putting +
and -
within a character class and use the following regex :
^(([0-9]{1,3})(\.[0-9]{1,3})?)([-+]([0-1](\.[0-9]{1,3}))|(\+([0-1](\.[0-9]{1,3}))(\-([0-1](\.[0-9]{1,3})))))$
In this case always you will have A
and after it there is B
or C
or BC
Explain :
Your regex will be AB
or AC
or ABC
so after A
you want B
or C
or BC
you can create the B
orC
with putting +
and -
within a character class:
([-+]([0-1](\.[0-9]{1,3}))
And then use pip (|
) as a logical or between the preceding option and BC
that is the following :
(\+([0-1](\.[0-9]{1,3}))(\-([0-1](\.[0-9]{1,3}))
Upvotes: 2
Reputation: 174696
Use three patterns separated by |
operator. To match AB
or AC
, just put B
or C
inside a non-capturing group with both patterns are separated by alternation operator.
(([0-9]{1,3})(\.[0-9]{1,3})?)(\+([0-1](\.[0-9]{1,3}))(-([0-1](\.[0-9]{1,3}))|(([0-9]{1,3})(\.[0-9]{1,3})?)(?:(\+([0-1](\.[0-9]{1,3}))|(-([0-1](\.[0-9]{1,3})))
|<-----------------------------------ABC----------------------------------->|<------------AB or AC----------------------------------------------------------->
Upvotes: 0
Reputation: 48807
Several solutions:
Write it as you say it: AB|AC|ABC
Avoid redundancy: A(BC?|C)
or A(B?C|B)
Upvotes: 1