I need to construct some regular expressions. I am facing issues with the listed below

  1. Find all words starting with a whose letters are all in alphabetical order. I tried - ^[a]a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*$ but it is not working.

    input:

    • ab - it fails to match it
  2. Find all words that contain no vowels and no y’s. I tried - [^aeiouy]+$ but it is not working

    input:

    • abc - not a match
    • bc - match
    • sgpty - not a match
    • sgpt - match
  3. Find all words that start with z and contain at least 2 y’s. I tried - r"\b[z].*(y.*?){2}\b" but it is not working properly. It matches the work but doesnot print it correctly (I am simply printing match from findAll() results, nothing else)

    input:

    • zygapophyses - match but print yses only
    • zygapophysis - match but print ysis only
  4. Find all words that consist of alternating vowels and consonants (in either order) and have length at least 12. I tried - ^(([aeiou][^aeiou])+|([^aeiou][aeiou])+)$ but don't know how to test the length for 12 or more characters.

    ^(([aeiou][^aeiou])+|([^aeiou][aeiou])+){12,}$ didn't work for me.

    input:

    • witenagemote - match
    • vituperative - match
    • vizirate - not a match
    • verisimilitude - match

1 Answers

1
Yusufsn On Best Solutions

This is one example for the 2nd question. Your regex is good enough.

import re
def find_word(word):
    if re.match("[^aeiouy]+$",word):
        print (word, "DOESN'T CONTAIN VOWELS OR Y")
    else:
        print (word, "CONTAINS VOWELS OR Y")

find_word("abc")
find_word("bc")
find_word("sgpty")
find_word("sgpt")

Output:

abc CONTAINS VOWELS OR Y
bc DOESN'T CONTAIN VOWELS OR Y
sgpty CONTAINS VOWELS OR Y
sgpt DOESN'T CONTAIN VOWELS OR Y

For the 3rd question, I also use your regex:

def find_z(string) : 
    regex = re.compile(r"\b[z].*(y.*?){2}\b")  
    for st in string.split():
        match_object = regex.findall(st) 
        if len(match_object) != 0 : 
            for word in match_object : 
                print(st)
        else: 
            print("Not match")

Output:

zygapophyses
zygapophysis
Not match
Not match