53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
import re
|
|
|
|
# ex 9
|
|
mots = ['a', 'aab', 'aaab', 'aabaab', 'baabaab', 'abaabaaabaaaab']
|
|
regExps = [r"aa*b", r'a(a|b)*', r'(aa*b)*', r'(a|aab)*', r'a*|aab*']
|
|
|
|
for r in regExps:
|
|
print("Match for regex '" + r + "' are :")
|
|
for mot in mots:
|
|
m = re.fullmatch('(' + r + ')', mot)
|
|
if m:
|
|
print(" " + mot)
|
|
|
|
|
|
# ex 11
|
|
def say_hello(text):
|
|
regex = r'([a-zA-Z]+)\.[a-zA-Z]+@umons\.ac\.be'
|
|
m = re.search(regex, text)
|
|
if m:
|
|
print("Hello " + m.group(1))
|
|
|
|
|
|
say_hello("jean.bob@umons.ac.be")
|
|
say_hello("Patrick.BOUl@umons.ac.be")
|
|
say_hello("s.ac.be")
|
|
|
|
|
|
# ex 12
|
|
def newlines(text,nbr):
|
|
regex = r'((\w+ ){'+str(nbr-1)+r'}\w+)|(\w+)'
|
|
m = re.findall(regex, text)
|
|
res = ""
|
|
if m:
|
|
for group in m:
|
|
mots = group[0].split(r" ")
|
|
if len(mots) == nbr:
|
|
for i in range(nbr):
|
|
res += str(i+1) + ". " + mots[i] + "\t"
|
|
res += "\n"
|
|
else:
|
|
res += " "+group[2]
|
|
|
|
return res
|
|
|
|
|
|
def newlines_with_varying_size(text, n=5):
|
|
pattern = r'\s+'.join(r'(\w+)' for _ in range(n))
|
|
group = [rf'{i}. \{i}' for i in range(1, n + 1)]
|
|
repl = '\t'.join(group) + '\n'
|
|
return re.sub(pattern, repl, text)
|
|
|
|
print(newlines('cet exercice travaille avec une suite de mots', 4))
|