Excercise on RegEX

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).

1 Like

import re
def spec_char(str):
char = re.compile(r’[^a-zA-Z0-9]')
str = char.search(str)
return not bool(str)

print(spec_char(“AbcDEfgH123456”))
print(spec_char(“*@#$%![}{]”))

1 Like

import re

user_input = input("Enter a string: ")

pattern = “^[a-zA-Z0-9]$”

find = re.match(pattern, user_input)

if find:
print(f"correct{user_input}")
else:
print(“none”)

1 Like

Very good. keep practicing.

def only_allowed_characters(input_string):
for char in input_string:
if not char.isalnum():
return False
return True

input_string = “Hello123”
result1 = only_allowed_characters(input_string)
print(f"Given_String: {input_string} contains only allowed characters: {result1}")

1 Like

import re

user_input = input("Enter a string: ")

pattern = ‘^[a-zA-Z0-9]+$’

find = re.match(pattern, user_input)

if find:
print(f"Matched string {user_input}")
else:
print(“None”)

1 Like

good. keep working on

You have to create search pattern which includes all the defined rules. keep working .

very good. keep practicing