Sunteți pe pagina 1din 39

Expresii Regulate în Python

re.findall('[a-z]+', text.lower())
În informatică, o expresie regulată, denumită pe
scurt regex sau regexp (din engleză - regular
expression), reprezintă un șablon care descrie un
limbaj regulat, adică o mulțime de șiruri de caractere
generată de o gramatică regulată.

Mulțimea de fișiere textuale

.*\.txt
Ghid rapid de Expresii regulate
^ Matches the beginning of a line
$ Matches the end of the line
. Matches any character
\s Matches whitespace
\S Matches any non-whitespace character
* Repeats a character zero or more times
*? Repeats a character zero or more times (non-greedy)
+ Repeats a character one or more times
+? Repeats a character one or more times (non-greedy)
[aeiou] Matches a single character in the listed set
[^XYZ] Matches a single character not in the listed set
[a-z0-9] The set of characters can include a range
( Indicates where string extraction is to start
) Indicates where string extraction is to end
Modulul Expresiilor Regulate
• Inițial trebuie să importați modulul "import re"
• Puteți să utilizați re.search() pentru a vedea
dacă un șir se potrivește cu expresia regulată
similar utilizînd metoda find() pentru șiruri
• Puteți să utilizați metoda re.findall() pentru a
extrage părți de șir ce se potrivesc expresiei
combinate cu find() și felierea: var[5:10]
Utilizare re.search() la fel ca find()

import re
hand = open('mbox-short.txt')
for line in hand: hand = open('mbox-short.txt')
line = line.rstrip() for line in hand:
if line.find('From:') >=0: line = line.rstrip()
print (line) if re.search('^From:', line) :
print (line)
Utilizare re.search() la fel ca
startswith()
import re
hand = open('mbox-short.txt')
hand = open('mbox-short.txt')
for line in hand:
for line in hand:
line = line.rstrip()
line = line.rstrip()
if line.startswith('From:'):
if re.search(‘^From:', line) :
print (line)
print(line)

We fine-tune what is matched by adding special characters to the string


Caractere Wild-Card
 Caracterul “.” potrivește orice caracter
 Dacă adăugați “*”, caracterul se citește “orice în număr
de multe ori”

X-Sieve: CMU Sieve 2.3 ^X.*:


X-DSPAM-Result: Innocent
X-DSPAM-Confidence: 0.8475
X-Content-Type-Message-Body: text/plain
Exactitatatea expresiei căutate

• Depinde cît de ”curate” sunt datele dvs. și


scopul aplicației, ați putea îngusta potrivirea

Mulează începutul liniei De Multe ori

^X.*:
Mulează orice caracter
Potrivirea (Mularea) și extragerea datelor

 Metoda re.search() returnează True/False în dependență


dacă șirul mulează cu expresia regulată
 Dacă dorim să extragem șirurile potrivite, vom utiliza
re.findall()

[0-9]+
Una sau mai multe cifre
Potrivirea (Mularea) și Extragerea datelor

 Când utilizăm metoda re.findall() ea returneazăo listă vidă sau mai


multe subșiruri ce se potrivesc cu expresia regulată
Atenție: Potrivire Greedy (lacomă)

 Caracterele de repetare (+ și *) ia din ambele părți(direcții)


potrivire cu cel mai mare subșir
Atenție: Potrivire Greedy (lacomă)

 Caracterele de repetare (+ și *) ia din ambele părți(direcții)


potrivire cel mai mare subșir

['From: Using the :']


>>>
Potrivire Non-Greedy (nelacomă)

 Semnul ? dacă îl adăugăm după semnele de repetare (* și


+) vom avea:
Potrivire Non-Greedy (nelacomă)

 Semnul ? dacă îl adăugăm după semnele de repetare (* și


+) vom avea:

['From:']
>>>
Extragerea fină a unui subșir dintr-un șir
 Putem să redefinim expresia pentru re.findall() și să determinăm
separat care porțiune din expresie să fie extrasă utilizînd parantezele
()
Extragerea fină a unui subșir dintr-un șir
 Putem să redefinim expresia pentru re.findall() și să determinăm
separat care porțiune din expresie să fie extrasă utilizînd parantezele
()

['ion.mard@mail.utm.md']
>>>
Extragerea fină a unui subșir dintr-un șir
 Parantezele ne arată de unde să începem și unde să
sfârșim extragerea subșirului

['ion.mard@mail.utm.md']
['ion.mard@mail.utm.md']
>>>
Validarea mail-ului
Funcțiile și metodele modulului re

 Compile(), findall(), finditer(), fullmatch(),


match(), purge(), search(), sub(), subn(),
template(), split()
Funcțiile și metodele modulului re
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)


Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used.
Înlocuirea

>>> print (re.sub("Bine ai venit la (?


P<la_cine>\w+)! Tu ai (?P<virsta>\d+) ani ?",
"\g<la_cine> are \g<virsta> ani", "Bine ai venit la
olivier! Tu ai 32 ani"))
olivier are 32 ani
>>>
FUNCTIONS

match Match a regular expression pattern to the


beginning of a string.
fullmatch Match a regular expression pattern to all of
a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a
string.
subn Same as sub, but also return the number of
substitutions made.
split Split a string by the occurrences of a pattern.
FUNCTIONS

findall Find all occurrences of a pattern in a string.


finditer Return an iterator yielding a match object
for each match.
compile Compile a pattern into a RegexObject.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
FUNCTIONS
compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.

escape(pattern)
Escape all the characters in pattern except ASCII letters, numbers and
'_'.

findall(pattern, string, flags=0)


Return a list of all non-overlapping matches in the string.

If one or more capturing groups are present in the pattern, return


a list of groups; this will be a list of tuples if the pattern
has more than one group.

Empty matches are included in the result.


finditer(pattern, string, flags=0)
Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object.

Empty matches are included in the result.

fullmatch(pattern, string, flags=0)


Try to apply the pattern to all of the string, returning
a match object, or None if no match was found.

match(pattern, string, flags=0)


Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.

purge()
Clear the regular expression caches
search(pattern, string, flags=0)
Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found.

split(pattern, string, maxsplit=0, flags=0)


Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list.

sub(pattern, repl, string, count=0, flags=0)


subn(pattern, repl, string, count=0, flags=0)
Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used.

template(pattern, flags=0)
Compile a template pattern, returning a pattern object
Verificarea expresiei regulate online

 https://regex101.com/
 http://
www.regular-expressions.info/python.
html
 https://
regexone.com/references/python
v
Validarea e-mailului
Găsirea poziției
Găsirea poziției

Potrivirea la index: 0, 7
Potrivirea la index: 9, 17
Potrivirea la index: 19, 25
>>>
Match at index 0, 7
Full match: June 24
Month: June
Day: 24
>>>
^ matches the beginning of a string.
$ matches the end of a string.
\b matches a word boundary.
\d matches any numeric digit.
\D matches any non-numeric character.
x? matches an optional x character (in other words, it matches an x zero or
one times).
x* matches x zero or more times.
x+ matches x one or more times.
x{n,m} matches an x character at least n times, but not more than m times.
(a|b|c) matches exactly one of a, b or c.
(x) in general is a remembered group. You can get the value of what
matched by using the groups() method of the object returned by re.search.
Șablon pentru a identifica numărul de
telefon
 +373 22 34 56 54
 +(373) 22 34-56-54
 0 0 373 22 345653
 0 22 34-56-67
 (022) 345467
 (022) 34-34-56
 022 34.45.67
Sumar

 Expresii regulate

S-ar putea să vă placă și