Question

In: Computer Science

Pattern matching using python3 re module Write a regular expression that will find out all the...

Pattern matching using python3 re module

Write a regular expression that will find out all the words that ends with 4 consecutive vowels at the end.

Example: import re

f=open("/usr/share/dict/american-english",'r')

pattern='a[a-z]*d$'

words=f.readlines()

matchlist=[word for word in words if re.match(pattern,word)]

===============================

Generate random string follow a specific pattern

You will take a username and ask user for the password. User has to enter a strong password in order to create his or her account. The criteria for strong password is, a) Starts with a letter a to z or A to Z b) Cannot end with a digit c) Total character should be 10 d) The character can be letter a to z or A to Z or digit 0 to 9 or _

You will show a message that account is successfully created if user enters a strong password. If a user does not enter a strong password, you will reject the user entered password and generate a strong password as follows: a) Starts with the first character of the user’s user name b) Ends with the last character of the user’s user name c) Total character should be 10 d) The character can be letter a to z or A to Z or digit 0 to 9 or _

Sample output: Account is successfully created

Another sample output: Week Password

Generating a Strong Password

The auto generated password: j57m9XoUGa

Solutions

Expert Solution

Question #1

The program is given below. The comments are provided for the better understanding of the logic.

import re

#Provide the filename here.  If it is in a separate directory, the full path has to be entered here.
#Assumed that the file has only one word per line.
#If this is not the case, logic has to be altered.
inputFile = "words.txt"

#Open the file in read only mode
fileHandler = open(inputFile,"r") 

#Read the 1st line
line = fileHandler.readline()

#This loop will iterate as long as there are lines in the file.
while(line):
    #Trim the extra line breaks at the end.
    line = line.strip()
    
    #Check if the line matches the pattern "[aeiou]{4}$".  This is for matching any letter ending with 4 vowels.
    match = re.search("[aeiou]{4}$", line.lower())
    
    #Print the word if there is a match
    if(not (match is None)):
        print(line)
    
    #Read the next line for the loop to continue.
    line = fileHandler.readline()

#Close the file.
fileHandler.close() 

The screenshots of the code and output are provided below.

Question #2

The program is given below. The comments are provided for the better understanding of the logic.

import re
import random
import string

#Prompt for the username and password.
#And store it in variables
username = input("Enter your username: ")
password = input("Enter your password: ")

#Check if the password entered matches all the rules given.
#In the below regex pattern
#[a-zA-Z] matches a single alphabet in lower or upper case
#[a-zA-Z0-9_]{8} matches alphabets or digits or an underscore.  It has to be exactly 8 characters.
#[a-zA-z_] matches a single character. It can be alphabet or underscore.  The rule given is that the password cannot end with a digit.  Hence coded like this.
match = re.search("^[a-zA-Z][a-zA-Z0-9_]{8}[a-zA-z_]$", password)
if(match is None):
    #If there is no match, a week password is entered.
    #Generate a new password
    print("This is a Week Password")
    print("Generating a Strong Password")
    
    #This cariable stores lowercase and uppercase letters, digits and underscore.
    characterSequence = string.ascii_lowercase + string.ascii_uppercase + "0123456789_"
    generatedPassword = ""
    
    #This loop iterates from 0 to 7.
    for i in range(8):
        #The random.choice function randomly select a character from the characterSequence variable
        generatedPassword = generatedPassword + random.choice(characterSequence)
    
    #at the end of the above loop, the variable generatedPassword will have a 8 length random set of characters.
    #prefix with 1st letter of the username and suffix with the last letter of the username.
    #Thus forming a 10 character password.
    generatedPassword = username[0] + generatedPassword + username[len(username)-1]
    
    #Display the password to the user.
    print("The auto generated password: ", end = "")
    print(generatedPassword)
else:
    #If the user entered a proper password, print a success message.
    print("The account is successfully created.")


Related Solutions

Q1 Write a python regular expression to match a certain pattern of phone number.             ###...
Q1 Write a python regular expression to match a certain pattern of phone number.             ### Suppose we want to recognize phone numbers with or without hyphens. The ### regular expression you give should work for any number of groups of any (non- ### empty) size, separated by 1 hyphen. Each group is [0-9]+. ### Hint: Accept "5" but not "-6" ### FSM for TELEPHONE NUMBER IS: # state:1 --[0-9]--> state:2 # state:2 --[0-9]--> state:4 # state:2 --[\-]---> state:3 #...
Write the correct regular expression pattern for a phone number field with the format XXX-XXX-XXXX
Write the correct regular expression pattern for a phone number field with the format XXX-XXX-XXXX
write a regular expression that will, using capturing groups, find: last name first name middle name...
write a regular expression that will, using capturing groups, find: last name first name middle name (if available) student ID rank home phone work phone (if available) email program (i.e., S4040) grade Replace the entire row with comma-delimited values in the following order: first name,middle name,last name,program,rank,grade,email,student ID,home phone,work phone Example substitution string for the first student Jane,V,Quinn,S4040,SO,B,[email protected],Q43-15-5883,318-377-4560,318-245-1144,Y
1. What is a regular expression? Write a regular expression that will detect “College” and “collegE”....
1. What is a regular expression? Write a regular expression that will detect “College” and “collegE”. 2. What is degree centrality? Create a graph of 4 vertices and compute the degree centrality of the vertices. 3. Compute internal and external community densities for a graph containing 6 nodes. You can create any graph of 6 nodes with at least 4 edges.
Write a regular expression for the language of all strings over {a,b} in which every b...
Write a regular expression for the language of all strings over {a,b} in which every b is directly preceded by a, and may not be directly followed by more than two consecutive a symbols.
Regular Expressions Assignment Write a regular expression for each of the following. Can you show output...
Regular Expressions Assignment Write a regular expression for each of the following. Can you show output please. A blank line (may contain spaces) Postal abbreviation (2 letters) for State followed by a space and then the 5-digit zip code A KU student username (Ex. lpork247) A “valid” email address (also explain how you defined “valid”) A SSN pattern (ddd-dd-dddd)
In this assignment you will practice using the pattern-matching constructs described in chapter 7 of your...
In this assignment you will practice using the pattern-matching constructs described in chapter 7 of your textbook to write several short SML functions. If at all possible, write all functions using pattern-matching constructs.  Include your name as a comment in the file, like this (* John Q Adams *). To reiterate - Use the pattern matching constructs described in chapter 7 to define your functions. Do the two steps below: Download the following file to a folder. It contains dummy, hence...
1) Write an XPath expression to find all elements (anywhere in the input document) having a...
1) Write an XPath expression to find all elements (anywhere in the input document) having a born element anywhere inside them. 2) What does the XPath expression /html/body//div[1] return? 3) Write an XPath expression to find all elements (anywhere in the input document) that do not have an id attribute.
The phone numbers collected from questionnaire is a mess. Design a regular expression to filter out...
The phone numbers collected from questionnaire is a mess. Design a regular expression to filter out those numbers that are stored in the standard format         “+00-0-0000-0000” from the file called “Q1.txt” and redirect the results to the “cleaned.txt”. Note: Only +61-3-9214-4980 and +61-3-9285-7706 are the valid results.    [10 Marks]
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression...
Write a JAVA program that reads a text file into RAM efficiently, takes a regular expression from the user, and then prints every line that matches the RE.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT