Reputation: 1
I am searching for a number in this format.
[0-9]{3,6}[\-\/]{1}[0-9]{1,3}[\-\/]{1}[0-9]{1,2}
Is there a way how to define that there should be always only slash/ or colom- ? In other words, option that first one is - and the second one / should be omitted.
Upvotes: 0
Views: 34
Reputation: 89584
You can also use an alternation:
[0-9]{3,6}(-[0-9]{1,3}-|\/[0-9]{1,3}\/)[0-9]{1,2}
It's a basic idea but it works.
Upvotes: 0
Reputation: 425238
The general solution to this is to leave for basic regex as-is, but add a look ahead to assert various over-arching requirements:
^(?!.*-.*/|.*/.*-)[0-9]{3,6}[\-\/]{1}[0-9]{1,3}[\-\/]{1}[0-9]{1,2}
The (negative) look ahead (?!.*-.*/|.*/.*-)
means "in the following input, there is neither a - then a /, or a / then a -.
Although you could probably do it without a look ahead, it's easier to understand with a look ahead, plus you can add as many of these as you need as other requirements come along.
Upvotes: 0
Reputation: 16089
Yes, you can use the \1
back-reference. This matches the same character (or group) as the first matching group. In this case, the ([-\/])
is the first matching group and \1
requires to be the same character.
[0-9]{3,6}([-\/])[0-9]{1,3}\1[0-9]{1,2}
Here is an example: https://regex101.com/r/mKxnUN/1
Upvotes: 1