Athanor
Athanor

Reputation: 955

Logical OR in regex

I want to test using java regex the following cases:

Here are the A, B and C regex:

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

Answers (3)

Kasravnd
Kasravnd

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 BorC 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

Avinash Raj
Avinash Raj

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

sp00m
sp00m

Reputation: 48807

Several solutions:

  1. Write it as you say it: AB|AC|ABC

  2. Avoid redundancy: A(BC?|C) or A(B?C|B)

Upvotes: 1

Related Questions