Python Normal İfade
Bir RegEx veya Normal İfade, bir arama kalıbı oluşturan bir karakter dizisidir.
RegEx, bir dizenin belirtilen arama modelini içerip içermediğini kontrol etmek için kullanılabilir.
Normal İfade Modülü
re
Python, Normal İfadelerle çalışmak için kullanılabilecek yerleşik bir pakete sahiptir .
re
Modülü içe aktarın :
import re
Python'da RegEx
Modülü içe re
aktardığınızda, normal ifadeleri kullanmaya başlayabilirsiniz:
Örnek
"The" ile başlayıp "İspanya" ile bitip bitmediğini görmek için dizeyi arayın:
import
re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
Normal İfade İşlevleri
Modül re
, bir eşleşme için bir dizi aramamıza izin veren bir dizi işlev sunar:
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 |
meta karakterler
Meta karakterler, özel bir anlamı olan karakterlerdir:
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 |
Özel Diziler
Özel bir dizi, \
aşağıdaki listedeki karakterlerden birinin ardından gelir ve özel bir anlamı vardır:
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" |
Setler
[]
Küme, bir çift köşeli parantez içindeki özel bir anlamı olan bir karakter kümesidir :
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 |
findall() İşlevi
İşlev findall()
, tüm eşleşmeleri içeren bir liste döndürür.
Örnek
Tüm eşleşmelerin bir listesini yazdırın:
import re
txt = "The rain in Spain"
x = re.findall("ai",
txt)
print(x)
Liste, eşleşmeleri bulundukları sırayla içerir.
Eşleşme bulunamazsa boş bir liste döndürülür:
Örnek
Eşleşme bulunamazsa boş bir liste döndür:
import re
txt = "The rain in Spain"
x = re.findall("Portugal",
txt)
print(x)
arama() Fonksiyonu
İşlev search()
, dizede eşleşme arar ve eşleşme varsa Match nesnesini döndürür.
Birden fazla eşleşme varsa, eşleşmenin yalnızca ilk geçtiği yer döndürülür:
Örnek
Dizedeki ilk boşluk karakterini arayın:
import re
txt = "The rain in Spain"
x = re.search("\s",
txt)
print("The first white-space character is located in
position:", x.start())
Eşleşme bulunamazsa, değer None
döndürülür:
Örnek
Eşleşme döndürmeyen bir arama yapın:
import re
txt = "The rain in Spain"
x = re.search("Portugal",
txt)
print(x)
split() Fonksiyonu
İşlev split()
, dizenin her eşleşmede bölündüğü bir liste döndürür:
Örnek
Her beyaz boşluk karakterinde bölün:
import re
txt = "The rain in Spain"
x = re.split("\s",
txt)
print(x)
maxsplit
Parametreyi belirterek oluşum sayısını kontrol edebilirsiniz
:
Örnek
Dizeyi yalnızca ilk oluşumda bölün:
import re
txt = "The rain in Spain"
x = re.split("\s",
txt,
1)
print(x)
alt() İşlevi
İşlev sub()
, eşleşmeleri seçtiğiniz metinle değiştirir:
Örnek
Her boşluk karakterini 9 sayısıyla değiştirin:
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt)
print(x)
Parametreyi belirterek değiştirme sayısını kontrol edebilirsiniz
count
:
Örnek
İlk 2 oluşumu değiştirin:
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt, 2)
print(x)
Nesneyi Eşleştir
Eşleşme Nesnesi, arama ve sonuç hakkında bilgi içeren bir nesnedir.
Not: Eşleşme yoksa, Eşleşme Nesnesi yerine değer None
döndürülür.
Örnek
Bir Eşleşme Nesnesi döndürecek bir arama yapın:
import re
txt = "The rain in Spain"
x = re.search("ai",
txt)
print(x) #this will print an object
Match nesnesi, arama ve sonuç hakkında bilgi almak için kullanılan özelliklere ve yöntemlere sahiptir:
.span()
eşleşmenin başlangıç ve bitiş konumlarını içeren bir demet döndürür.
.string
işleve iletilen dizeyi döndürür, dizenin
.group()
eşleşme olan bölümünü döndürür
Örnek
İlk eşleşme oluşumunun konumunu (başlangıç ve bitiş konumu) yazdırın.
Normal ifade, büyük harf "S" ile başlayan tüm kelimeleri arar:
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
Örnek
İşleve iletilen dizeyi yazdırın:
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
Örnek
Dizenin eşleşme olan kısmını yazdırın.
Normal ifade, büyük harf "S" ile başlayan tüm kelimeleri arar:
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
Not: Eşleşme yoksa, Eşleşme Nesnesi yerine değer None
döndürülür.