Reputation: 2101
I need to match a string with specific letters but none of the letters should be duplicated. For example, [AEIOU] should not match 'AAEIOU' or 'AAEEIOU'. It should only match 'AEIOU' and the order of the letters should not matter. I tried using the exact quantifier with {} but did not work.
Upvotes: 1
Views: 1255
Reputation: 41051
Not using regex, but you can use python string methods to count characters in a string. This can be used to develop a filter function that, effectively, can get you the results you want.
def has_all_unique(s):
"""Returns True of the string has exactly 1 of each vowel"""
return all(s.count(char) == 1 for char in 'AEIOU')
tests = ['AAEIOU', 'AAEEIOU', 'AEIOU']
for match in filter(has_all_unique, tests):
print(match)
Result would be just the one match meeting the condition,
AEIOU
This isn't the most performant option, but is simple and readable.
Upvotes: 0
Reputation: 51165
You can use negative lookahead:
Whatever you put in the brackets will be the subset of characters you select from.
>>> import re
>>> tests = ['AAEIOU', 'AAEEIOU', 'AEIOU']
>>> for test in tests:
.. print(re.match(r'^(?!.*(.).*\1)[AEIOU]+$', test))
None
None
<_sre.SRE_Match object; span=(0, 5), match='AEIOU'>
Upvotes: 2
Reputation: 81
This maybe inefficient, but maybe use counters? Construct a counter for each, then check if they are equal?
Upvotes: 0