Chris
Chris

Reputation: 182

How to create an exclusive or using regex

I would like to write a regex script to match both of below samples:

a/b/c
a1/a2/b/c

(note: a,a1,a2,b,c are all positive integers). The challenge to me is that I need to be able to capture the value of each variable.

I tried something like (\d+|(\d+\/\d+))\/\d+\/\d+. But the | calculator seems working as an inclusive or rather than exclusive one.

Is there any way I could write an exclusive or?

I am also open to other solutions.

Thank you!

Upvotes: 0

Views: 95

Answers (2)

Valdi_Bo
Valdi_Bo

Reputation: 30971

You try to capture at least 3 numbers, separated with /, plus possibly another / and a number.

So the intuitive regex is:

(\d+)/(\d+)/(\d+)(?:/(\d+))?

The "tail" (final / and a number) is the content of the final non-capturing group. (?:...)? makes the group optional and is not counted (but the parenthesis inside is).

Note: if you are using Perl flavor (i.e. using / as delimiters, you need to replace / by \/).

Upvotes: 1

Chuancong Gao
Chuancong Gao

Reputation: 660

Have a try on this one: (?:(\d+)(?:/(\d+))?)/(\d+)/(\d+).

Here the second group is an optional match. Note that I also used non-capturing group (?:sth), which does not count into groups.

For example, for 1/2/3/4, the groups are: Group 1. 1 Group 2. 2 Group 3. 3 Group 4. 4

For 1/3/4, the groups are: Group 1. 1 Group 3. 3 Group 4. 4

Upvotes: 0

Related Questions