This repository has been archived on 2026-03-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
TP-CMPL/TP1.py
2022-03-05 21:56:48 +01:00

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