I need to check if a string is formed by the continuous pattern of alternating vowels and consonants and vice versa is a valid pattern string or not..,here is my code
import re
s1="japan"
s2="iran"
s3="brazil"
pattern=re.compile(r'^(([aeiou][^aeiou]) |([^aeiou][aeiou]) )$')
matching1=re.match(pattern,s1)
matching2=re.match(pattern,s2)
matching3=re.match(pattern,s3)
if(matching1):
print(f"{s1} follows a valid pattern")
else:
print(f"{s1} does not follows a valid pattern")
so, what i am trying to do is, i need to return string s1 as a valid pattern string,because Jis a consonant , A is a vowel , P is a consonant,A is a vowel ,N is a consonant
and similarly; s2 as a valid pattern string
and s3 as an invalid pattern string.
but what i got is, S1 and S3 as an invalid pattern string
and s2 as a valid pattern string and that too failed if i put another vowel lets say A and make it as irana
CodePudding user response:
Your regexp only matches if there are an even number of characters. The alternative that's vowel-consonant needs to allow an optional vowel at the end, and vice versa for the other alternative.
pattern=re.compile(r'^(([aeiou][^aeiou]) [aeiou]?|([^aeiou][aeiou]) [^aeiou]?)$')
CodePudding user response:
An alternative, search for two consecutive consonants/vowels:
import re
test_cases = ["japan", "iran", "brazil"]
pat = re.compile(r"[aeiou]{2,}|[^aeiou]{2,}")
for t in test_cases:
if pat.search(t):
print(f"{t} does not follows a valid pattern")
else:
print(f"{t} follows a valid pattern")
Prints:
japan follows a valid pattern
iran follows a valid pattern
brazil does not follows a valid pattern
