Pythonチュートリアル

Pythonホーム Pythonイントロ Pythonはじめに Python構文 Pythonコメント Python変数 Pythonデータ型 Python番号 Pythonキャスティング Python文字列 Pythonブール値 Python演算子 Pythonリスト Pythonタプル Pythonセット Python辞書 Python If ... Else PythonのWhileループ PythonForループ Python関数 Python Lambda Python配列 Pythonクラス/オブジェクト Pythonの継承 Pythonイテレータ Pythonスコープ Pythonモジュール Pythonの日付 Python数学 Python JSON Python RegEx Python PIP Python試してみてください... Pythonユーザー入力 Python文字列フォーマット

ファイル処理

Pythonファイル処理 Python読み取りファイル Python書き込み/ファイルの作成 Pythonファイルの削除

Pythonモジュール

NumPyチュートリアル パンダ攻略 Scipyチュートリアル

Python Matplotlib

Matplotlibイントロ Matplotlibはじめに Matplotlib Pyplot Matplotlibプロット Matplotlibマーカー Matplotlibライン Matplotlibラベル Matplotlibグリッド Matplotlibサブプロット Matplotlib散布図 Matplotlibバー Matplotlibヒストグラム Matplotlib円グラフ

機械学習

入門 平均中央値モード 標準偏差 パーセンタイル データ配信 正規データ分布 散布図 線形回帰 多項式回帰 重回帰 規模 トレーニング/テスト デシジョンツリー

Python MySQL

MySQLはじめに MySQLデータベースの作成 MySQLテーブルの作成 MySQL挿入 MySQL Select MySQL Where MySQL Order By MySQL削除 MySQLドロップテーブル MySQLアップデート MySQLの制限 MySQL参加

Python MongoDB

MongoDBはじめに MongoDBデータベースの作成 MongoDBCreateコレクション MongoDBインサート MongoDB検索 MongoDBクエリ MongoDBソート MongoDB削除 MongoDBドロップコレクション MongoDBアップデート MongoDBの制限

Pythonリファレンス

Pythonの概要 Python組み込み関数 Python文字列メソッド Pythonリストメソッド Python辞書メソッド Pythonタプルメソッド Pythonセットメソッド Pythonファイルメソッド Pythonキーワード Pythonの例外 Python用語集

モジュールリファレンス

ランダムモジュール リクエストモジュール 統計モジュール 数学モジュール cMathモジュール

Pythonハウツー

リストの重複を削除する 文字列を逆にする 2つの数字を追加する

Pythonの例

Pythonの例 Pythonコンパイラ Python演習 Pythonクイズ Python証明書

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一致するものがない場合は、一致オブジェクトではなく値が返されます。