Computer Code Python CCP 17 : expressions régulières 4

in fr •  7 years ago  (edited)

Table of Contents

  1. Correspondance avec un nombre précis de répétitions
  2. Correspondance gloutonne et non gloutonne
  3. La méthode findall()
  4. Bilan
  5. Pour aller plus loin

Correspondance avec un nombre précis de répétitions

import re

mouhaRegex = re.compile(r'mou(Ha){4}')

mo1 = mouhaRegex.search('mouHaHaHaHa')
print(mo1.group())

mo2 = mouhaRegex.search('mouHaHa')
if mo2 == None:
    print('Pattern not found')

Correspondance gloutonne et non gloutonne

import re

greedyHaRegex = re.compile(r'(Ha){3,5}')

mo1 = greedyHaRegex.search('HaHaHaHaHa')
print(mo1.group())

nonGreedyHaRegex = re.compile(r'(Ha){3,5}?')
mo2 = nonGreedyHaRegex.search('HaHaHaHaHa')
print(mo2.group())

La méthode findall()

import re

phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

mo = phoneRegex.search('Cell: 415-555-9999 Work: 212-555-0000')
print(mo.group())

print(phoneRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))

phoneRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
print(phoneRegex.findall('Cell: 415-555-9999 Work: 212-555-0000'))

Bilan

Nous avons vu dans ce cours :

  • comment gérer un nombre spécifique de répétition
  • comment gérer la correspondance gloutonne et non gloutonne
  • comment utiliser la méthode findall()

Pour aller plus loin

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!