Python RegEx
RegEx、または正規表現は、検索パターンを形成する文字のシーケンスです。
RegExを使用して、文字列に指定された検索パターンが含まれているかどうかを確認できます。
RegExモジュール
Pythonには、re
正規表現を操作するために使用できる、と呼ばれる組み込みパッケージがあります。
re
モジュールをインポートします。
import re
Pythonの正規表現
モジュールをインポートしたらre
、正規表現の使用を開始できます。
例
文字列を検索して、「The」で始まり「Spain」で終わるかどうかを確認します。
import
re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
正規表現関数
このre
モジュールは、文字列で一致するものを検索できるようにする一連の関数を提供します。
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 |
メタ文字
メタ文字は、特別な意味を持つ文字です。
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 |
特別なシーケンス
特別なシーケンスの\
後には、以下のリストの文字の1つが続き、特別な意味があります。
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" |
セット
[]
セットとは、特別な意味を持つ角かっこで囲まれた文字のセットです。
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()関数
このfindall()
関数は、すべての一致を含むリストを返します。
例
すべての一致のリストを印刷します。
import re
txt = "The rain in Spain"
x = re.findall("ai",
txt)
print(x)
リストには、見つかった順序で一致するものが含まれています。
一致するものが見つからない場合は、空のリストが返されます。
例
一致するものが見つからなかった場合は、空のリストを返します。
import re
txt = "The rain in Spain"
x = re.findall("Portugal",
txt)
print(x)
search()関数
このsearch()
関数は文字列で一致するものを検索し、一致する場合はMatchオブジェクトを返します。
複数の一致がある場合は、最初に一致したものだけが返されます。
例
文字列の最初の空白文字を検索します。
import re
txt = "The rain in Spain"
x = re.search("\s",
txt)
print("The first white-space character is located in
position:", x.start())
一致するものが見つからない場合、値None
が返されます。
例
一致しないものを返す検索を行います。
import re
txt = "The rain in Spain"
x = re.search("Portugal",
txt)
print(x)
split()関数
このsplit()
関数は、一致するたびに文字列が分割されたリストを返します。
例
各空白文字で分割:
import re
txt = "The rain in Spain"
x = re.split("\s",
txt)
print(x)
maxsplit
パラメータを指定することにより、発生回数を制御でき
ます。
例
最初の出現時にのみ文字列を分割します。
import re
txt = "The rain in Spain"
x = re.split("\s",
txt,
1)
print(x)
sub()関数
このsub()
関数は、一致を選択したテキストに置き換えます。
例
すべての空白文字を数字の9に置き換えます。
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt)
print(x)
count
パラメータを指定することにより、置換の数を制御でき
ます。
例
最初の2つのオカレンスを置き換えます。
import re
txt = "The rain in Spain"
x = re.sub("\s",
"9", txt, 2)
print(x)
一致オブジェクト
一致オブジェクトは、検索と結果に関する情報を含むオブジェクトです。
注:None
一致するものがない場合は、一致オブジェクトではなく値が返されます。
例
一致オブジェクトを返す検索を実行します。
import re
txt = "The rain in Spain"
x = re.search("ai",
txt)
print(x) #this will print an object
Matchオブジェクトには、検索と結果に関する情報を取得するために使用されるプロパティとメソッドがあります。
.span()
一致の開始位置と終了位置を含むタプルを返します。
.string
関数に渡された文字列を
.group()
返します一致した文字列の部分を返します
例
最初の一致オカレンスの位置(開始位置と終了位置)を出力します。
正規表現は、大文字の「S」で始まる単語を検索します。
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span())
例
関数に渡された文字列を出力します。
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string)
例
一致した文字列の部分を印刷します。
正規表現は、大文字の「S」で始まる単語を検索します。
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
注:None
一致するものがない場合は、一致オブジェクトではなく値が返されます。