Module 6 Regular Expressions Assignment
Module 6 Regular Expressions Assignment
Regular Expression
1) Write a Python program to check that a string contains only a certain set of characters.
(In this case a-z, A-Z, and 0-9).
import re
def contains_only_allowed_characters(input_string):
# Define a regular expression pattern to match the allowed characters
pattern = r'^[a-zA-Z0-9]+$'
# Test cases
input_string1 = "Hello123"
input_string2 = "Hello@123"
if contains_only_allowed_characters(input_string1):
print(f"'{input_string1}' contains only allowed characters.")
else:
print(f"'{input_string1}' contains disallowed characters.")
if contains_only_allowed_characters(input_string2):
print(f"'{input_string2}' contains only allowed characters.")
else:
print(f"'{input_string2}' contains disallowed characters.")
2) Write a Python program to replace all occurrences of space, commas, or dots with a
colon.
def replace_spaces_commas_dots_with_colon(input_string):
# Replace spaces, commas, and dots with a colon using the replace() method
modified_string = input_string.replace(' ', ':').replace(',', ':').replace('.', ':')
return modified_string
# Test case
original_string = "This is, a test. String with, spaces and.dots."
modified_string = replace_spaces_commas_dots_with_colon(original_string)
print("Original String:", original_string)
print("Modified String:", modified_string)