Python RegEx
Un RegEx, ou Regular Expression, est une séquence de caractères qui forme un modèle de recherche.
RegEx peut être utilisé pour vérifier si une chaîne contient le modèle de recherche spécifié.
Module RegEx
Python a un package intégré appelé re
, qui peut être utilisé pour travailler avec des expressions régulières.
Importez le re
module :
import re
RegEx en Python
Lorsque vous avez importé le re
module, vous pouvez commencer à utiliser des expressions régulières :
Exemple
Recherchez la chaîne pour voir si elle commence par "The" et se termine par "Spain":
import
re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
Fonctions RegEx
Le re
module propose un ensemble de fonctions qui nous permet de rechercher une chaîne pour une correspondance :
Function | Description |
---|---|
findall | Returns a list containing all matches |
search | Returns a Match object if there is a match anywhere in the string |
split | Returns a list where the string has been split at each match |
sub | Replaces one or many matches with a string |
Métacaractères
Les métacaractères sont des caractères ayant une signification particulière :
Character | Description | Example | Try it |
---|---|---|---|
[] | A set of characters | "[a-m]" | |
\ | Signals a special sequence (can also be used to escape special characters) | "\d" | |
. | Any character (except newline character) | "he..o" | |
^ | Starts with | "^hello" | |
$ | Ends with | "planet$" | |
* | Zero or more occurrences | "he.*o" | |
+ | One or more occurrences | "he.+o" | |
? | Zero or one occurrences | "he.?o" | |
{} | Exactly the specified number of occurrences | "he{2}o" | |
| | Either or | "falls|stays" | |
() | Capture and group |
Séquences spéciales
Une séquence spéciale est \
suivie par l'un des caractères de la liste ci-dessous et a une signification particulière :
Character | Description | Example | Try it |
---|---|---|---|
\A | Returns a match if the specified characters are at the beginning of the string | "\AThe" | |
\b | Returns a match where the specified characters are at the beginning or at the
end of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") |
r"\bain" r"ain\b" |
|
\B | Returns a match where the specified characters are present, but NOT at the beginning
(or at
the end) of a word (the "r" in the beginning is making sure that the string is being treated as a "raw string") |
r"\Bain" r"ain\B" |
|
\d | Returns a match where the string contains digits (numbers from 0-9) | "\d" | |
\D | Returns a match where the string DOES NOT contain digits | "\D" | |
\s | Returns a match where the string contains a white space character | "\s" | |
\S | Returns a match where the string DOES NOT contain a white space character | "\S" | |
\w | Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) | "\w" | |
\W | Returns a match where the string DOES NOT contain any word characters | "\W" | |
\Z | Returns a match if the specified characters are at the end of the string | "Spain\Z" |
Ensembles
Un ensemble est un ensemble de caractères à l'intérieur d'une paire de crochets
[]
ayant une signification particulière :
Set | Description | Try it |
---|---|---|
[arn] | Returns a match where one of the specified characters (a ,
r , or n ) are
present |
|
[a-n] | Returns a match for any lower case character, alphabetically between
a and n |
|
[^arn] | Returns a match for any character EXCEPT a ,
r , and n |
|
[0123] | Returns a match where any of the specified digits (0 ,
1 , 2 , or
3 ) are
present |
|
[0-9] | Returns a match for any digit between
0 and 9 |
|
[0-5][0-9] | Returns a match for any two-digit numbers from 00 and
59 |
|
[a-zA-Z] | Returns a match for any character alphabetically between
a and z , lower case OR upper case |
|
[+] | In sets, + , * ,
. , | ,
() , $ ,{}
has no special meaning, so [+] means: return a match for any
+ character in the string |
La fonction findall()
La findall()
fonction renvoie une liste contenant toutes les correspondances.
Exemple
Imprimez une liste de toutes les correspondances :
import re
txt = "The rain in Spain"
x = re.findall("ai",
txt)
print(x)
La liste contient les correspondances dans l'ordre où elles sont trouvées.
Si aucune correspondance n'est trouvée, une liste vide est renvoyée :
Exemple
Renvoie une liste vide si aucune correspondance n'a été trouvée :
import re
txt = "The rain in Spain"
x = re.findall("Portugal",
txt)
print(x)
La fonction recherche()
La search()
fonction recherche une correspondance dans la chaîne et renvoie un objet Match s'il y a une correspondance.
S'il y a plus d'une correspondance, seule la première occurrence de la correspondance sera renvoyée :
Exemple
Recherchez le premier caractère d'espace blanc dans la chaîne :
import re
txt = "The rain in Spain"
x = re.search("\s",
txt)
print("The first white-space character is located in
position:", x.start())
Si aucune correspondance n'est trouvée, la valeur None
est renvoyée :
Exemple
Effectuez une recherche qui ne renvoie aucune correspondance :
import re
txt = "The rain in Spain"
x = re.search("Portugal",
txt)
print(x)
La fonction split()
La split()
fonction renvoie une liste où la chaîne a été divisée à chaque correspondance :
Exemple
Fractionner à chaque caractère d'espace blanc :
import re
txt = "The rain in Spain"
x = re.split("\s",
txt)
print(x)
Vous pouvez contrôler le nombre d'occurrences en spécifiant le
maxsplit
paramètre :
Exemple
Fractionne la chaîne uniquement à la première occurrence :
import re
txt = "The rain in Spain"
x = re.split("\s",
txt,
1)
print(x)
La fonction sub()
La sub()
fonction remplace les correspondances par le texte de votre choix :
Exemple
Remplacez chaque caractère d'espace blanc par le chiffre 9 :
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt)
print(x)
Vous pouvez contrôler le nombre de remplacements en spécifiant le
count
paramètre :
Exemple
Remplacez les 2 premières occurrences :
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt, 2)
print(x)
Faire correspondre l'objet
Un Match Object est un objet contenant des informations sur la recherche et le résultat.
Remarque : S'il n'y a pas de correspondance, la valeur None
sera renvoyée à la place de l'objet de correspondance.
Exemple
Effectuez une recherche qui renverra un Match Object :
import re
txt = "The rain in Spain"
x = re.search("ai",
txt)
print(x) #this will print an object
L'objet Match possède des propriétés et des méthodes utilisées pour récupérer des informations sur la recherche et le résultat :
.span()
renvoie un tuple contenant les positions de début et de fin de la correspondance.
.string
renvoie la chaîne passée dans la fonction
.group()
renvoie la partie de la chaîne où il y avait une correspondance
Exemple
Imprimer la position (position de début et de fin) de la première occurrence de correspondance.
L'expression régulière recherche tous les mots commençant par un "S" majuscule :
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
Exemple
Affichez la chaîne transmise à la fonction :
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
Exemple
Imprimer la partie de la chaîne où il y avait une correspondance.
L'expression régulière recherche tous les mots commençant par un "S" majuscule :
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
Remarque : S'il n'y a pas de correspondance, la valeur None
sera renvoyée à la place de l'objet de correspondance.