I have a regex expression that accepts couples of uppercase characters separated by space:
^([A-Z]{2})([ ][A-Z]{2})*$
I want to make sure that every character appears only once:
for example, good input:
AB CD XY
not a good input:
AB BC
I have a regex expression that accepts couples of uppercase characters separated by space:
^([A-Z]{2})([ ][A-Z]{2})*$
I want to make sure that every character appears only once:
for example, good input:
AB CD XY
not a good input:
AB BC
You should prepend below regex to your regular expression:
(?!.*?([A-Z]).*\1)
But it should be just after caret ^
. I'm going to break it down:
(?!
Start of negative lookahead
.*?
Lazy dot-star to expand matching lazily([A-Z])
Match and capture a capital letter between A and Z.*
Greedy dot-star to expand matching greedily (it could be lazy)\1
Match whatever has been captured in previous capturing group)
End of negative lookaheadand entire regex would be:
^(?!.*?([A-Z]).*\1)([A-Z]{2})([ ][A-Z]{2})*$
See live demo here
But be careful that this changes the order of your capturing groups since it adds one capturing group before all others (so if they were captured in 1
and 2
now they are 2
and 3
). If you don't need to return them individually which means you don't need capturing groups then turn them to non-capturing groups:
^(?!.*?([A-Z]).*\1)[A-Z]{2}(?:[ ][A-Z]{2})*$
Because .NET supports infinite lookbehinds then a better approach would be utilizing this feature:
^[A-Z]{2}(?:[ ][A-Z]{2})*$(?<!\1.*([A-Z]).*?)
See live demo here