0% found this document useful (0 votes)
4 views

regex_solutions

Uploaded by

8jxbgbdcxs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

regex_solutions

Uploaded by

8jxbgbdcxs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

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 is_allowed_specific_char(string):
charRe = re.compile(r'[^a-zA-Z0-9.]')
string = charRe.search(string)
return not bool(string)

print(is_allowed_specific_char("ABCDEFabcdef123450"))
print(is_allowed_specific_char("*&%@#!}{"))

2. Write a Python program that matches a string that has an a followed by zero or
more b's.
import re
def text_match(text):
patterns = 'ab*?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("ac"))
print(text_match("abc"))
print(text_match("abbc"))

3. Write a Python program that matches a string that has an a followed by one or
more b's.

import re
def text_match(text):
patterns = 'ab+?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("ab"))
print(text_match("abc"))
4. Write a Python program that matches a string that has an a followed by zero or
one 'b'.
import re
def text_match(text):
patterns = 'ab?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("ab"))
print(text_match("abc"))
print(text_match("abbc"))
print(text_match("aabbc"))

5. Write a Python program that matches a string that has an a followed by three
'b'.
import re
def text_match(text):
patterns = 'ab{3}?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("abbb"))
print(text_match("aabbbbbc"))

6. Write a Python program that matches a string that has an a followed by two to
three 'b'.
import re
def text_match(text):
patterns = 'ab{2,3}?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("ab"))
print(text_match("aabbbbbc"))
7. Write a Python program to find sequences of lowercase letters joined with a
underscore.
import re
def text_match(text):
patterns = '^[a-z]+_[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("aab_cbbbc"))
print(text_match("aab_Abbbc"))
print(text_match("Aaab_abbbc"))

8. Write a Python program to find sequences of one upper case letter followed by
lower case letters.

import re
def text_match(text):
patterns = '^[a-z]+_[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("aab_cbbbc"))
print(text_match("aab_Abbbc"))
print(text_match("Aaab_abbbc"))

9. Write a Python program that matches a string that has an 'a' followed by
anything, ending in 'b'.
import re

def text_match(text):

patterns = 'a.*?b$'

if re.search(patterns, text):

return 'Found a match!'

else:

return('Not matched!')
print(text_match("aabbbbd"))

print(text_match("aabAbbbc"))

print(text_match("accddbbjjjb"))

10. Write a Python program that matches a word at the beginning of a string.
import re
def text_match(text):
patterns = '^\w+'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match(" The quick brown fox jumps over the lazy dog."))

11. Write a Python program that matches a word at end of string, with optional
punctuation.
import re
def text_match(text):
patterns = '\w+\S*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match("The quick brown fox jumps over the lazy dog. "))
print(text_match("The quick brown fox jumps over the lazy dog "))

12. Write a Python program that matches a word containing 'z'.


import re
def text_match(text):
patterns = '\w*z.\w*'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match("Python Exercises."))

13. Write a Python program that matches a word containing 'z', not start or end of
the word.
import re
def text_match(text):
patterns = '\Bz\B'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match("Python Exercises."))

14. Write a Python program to match a string that contains only upper and
lowercase letters, numbers, and underscores.

import re
def text_match(text):
patterns = '^[a-zA-Z0-9_]*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')

print(text_match("The quick brown fox jumps over the lazy dog."))


print(text_match("Python_Exercises_1"))

15. Write a Python program where a string will start with a specific number.

import re
def match_num(string):
text = re.compile(r"^5")
if text.match(string):
return True
else:
return False
print(match_num('5-2345861'))
print(match_num('6-2345861'))

16. Write a Python program to remove leading zeros from an IP address.


import re
ip = "216.08.094.196"
string = re.sub('\.[0]*', '.', ip)
print(string)

17. Write a Python program to check for a number at the end of a string.
import re
def end_num(string):
text = re.compile(r".*[0-9]$")
if text.match(string):
return True
else:
return False

print(end_num('abcdef'))
print(end_num('abcdef6'))

18. Write a Python program to search the numbers (0-9) of length between 1 to 3
in a given string.

"Exercises number 1, 12, 13, and 345 are important"


import re
results = re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13,
and 345 are important")
print("Number of length 1 to 3")
for n in results:
print(n.group(0))

20. Write a Python program to search a literals string in a string and also find the
location within the original string where the pattern occurs.

Sample text : 'The quick brown fox jumps over the lazy dog.'
Searched words : 'fox'

import re
pattern = 'fox'
text = 'The quick brown fox jumps over the lazy dog.'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "%s" in "%s" from %d to %d ' % \
(match.re.pattern, match.string, s, e))

26. Write a Python program to match if two words from a list of words starting
with letter 'P'.
import re

# Sample strings.
words = ["Python PHP", "Java JavaScript", "c c++"]

for w in words:
m = re.match("(P\w+)\W(P\w+)", w)
# Check for success
if m:
print(m.groups())

28. Write a Python program to find all words starting with 'a' or 'e' in a given
string.
import re
# Input.
text = "The following example creates an ArrayList with a capacity of
50 elements. Four elements are then added to the ArrayList and the
ArrayList is trimmed accordingly."
#find all the words starting with 'a' or 'e'
list = re.findall("[ae]\w+", text)
# Print result.
print(list)

31. Write a Python program to replace all occurrences of space, comma, or dot
with a colon.

import re
text = 'Python Exercises, PHP exercises.'
print(re.sub("[ ,.]", ":", text))

32. Write a Python program to replace maximum 2 occurrences of space,


comma, or dot with a colon.

import re
text = 'Python Exercises, PHP exercises.'
print(re.sub("[ ,.]", ":", text, 2))
36. Write a python program to convert camel case string to snake case string.

def camel_to_snake(text):
import re
str1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', str1).lower()

print(camel_to_snake('PythonExercises'))

37. Write a python program to convert snake case string to camel case string.
def snake_to_camel(word):
import re
return ''.join(x.capitalize() or '_' for x in word.split('_'))

print(snake_to_camel('python_exercises'))

38. Write a Python program to extract values between quotation marks of a


string.
import re
text1 = '"Python", "PHP", "Java"'
print(re.findall(r'"(.*?)"', text1))

39. Write a Python program to remove multiple spaces in a string.

import re
text1 = 'Python Exercises'
print("Original string:",text1)
print("Without extra spaces:",re.sub(' +',' ',text1))

40. Write a Python program to remove all whitespaces from a string.


import re
text1 = ' Python Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1))

42. Write a Python program to find urls in a string.

import re
text = '<p>Contents :</p><a href="https://w3resource.com">Python
Examples</a><a href="http://github.com">Even More Examples</a>'
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-
_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)
print("Original string: ",text)
print("Urls: ",urls)

43. Write a Python program to split a string at uppercase letters.


import re
text = "PythonTutorialAndExercises"
print(re.findall('[A-Z][^A-Z]*', text))

44. Write a Python program to do a case-insensitive string replacement.


import re
text = "PHP Exercises"
print("Original Text: ",text)
redata = re.compile(re.escape('php'), re.IGNORECASE)
new_text = redata.sub('Python', 'PHP Exercises')
print("Using 'php' replace PHP")
print("New Text: ",new_text)

48. Write a Python program to check a decimal with a precision of 2.


def is_decimal(num):
import re
dnumre = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
result = dnumre.search(num)
return bool(result)

print(is_decimal('123.11'))
print(is_decimal('123.1'))
print(is_decimal('123'))
print(is_decimal('0.21'))

print(is_decimal('123.1214'))
print(is_decimal('3.124587'))
print(is_decimal('e666.86'))

49. Write a Python program to remove words from a string of length between 1
and a given number.
import re
text = "The quick brown fox jumps over the lazy dog."
# remove words between 1 and 3
shortword = re.compile(r'\W*\b\w{1,3}\b')
print(shortword.sub('', text))

50. Write a Python program to remove the parenthesis area in a string.


Sample data : ["example (.com)", "w3resource", "github (.com)", "stackoverflow
(.com)"]
Expected Output:
example
w3resource
github
stackoverflow

import re
items = ["example (.com)", "w3resource", "github (.com)",
"stackoverflow (.com)"]
for item in items:
print(re.sub(r" ?\([^)]+\)", "", item))

51. Write a Python program to insert spaces between words starting with capital
letters.
import re
def capital_words_spaces(str1):
return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)

print(capital_words_spaces("Python"))
print(capital_words_spaces("PythonExercises"))
print(capital_words_spaces("PythonExercisesPracticeSolution"))

You might also like