Python 正規表現: re.match()、re.search()、re.findall() と例
⚡ スマートサマリー
Python 正規表現チュートリアルでは、re.match、re.search、re.findall、re.split を実践的な例を通して解説します。 Less本書では、メタ文字、文字クラス、グループ、フラグ、置換、およびテキスト解析と検証のための一般的なパターンについて説明します。
正規表現とは Python?
A 正規表現 (RE) プログラミング言語では、検索パターンを記述するために使用される特別なテキスト文字列です。これは、tracコード、ファイル、ログ、スプレッドシート、あるいは文書などのテキストから情報を抽出する。
を使用して Python 正規表現で最初に認識すべきことは、すべてが本質的に文字であり、文字列とも呼ばれる特定の文字シーケンスに一致するパターンを記述しているということです。ASCII またはラテン文字はキーボード上にある文字であり、Unicode は外国語のテキストに一致するために使用されます。これには、数字、句読点、$#@!% などのすべての特殊文字が含まれます。
例えば、 Python 正規表現は、文字列から特定のテキストを検索し、それに応じて結果を出力するようにプログラムに指示することができます。式には以下を含めることができます。
- テキストマッチング
- 繰り返し
- 分岐
- 柄構成など
正規表現またはRegEx Python RE(RE、正規表現、または正規表現パターン)として表され、 再モジュール. Python ライブラリを通じて正規表現をサポートします。 Python さまざまなものをサポートしています 修飾子、識別子、および空白文字.
| 識別子 | 修飾子 | 空白文字 | エスケープが必要です |
|---|---|---|---|
| \d= 任意の数字 (数字) | \d は数字を表します。例: \d{1,5} は、1,5 などの 424,444,545 の間の数字を宣言します。 | \n = 改行 | 。 + * ? [] $ ^ () {} | \ |
| \D= 数字以外 (数字以外) | + = 1 つ以上に一致します | \s= スペース | |
| \s = スペース (タブ、スペース、改行など) |
? = 0 または 1 に一致します | \t =タブ | |
| \S= スペース以外のもの | * = 0 以上 | \e = 逃げる | |
| \w = letters ( Match alphanumeric character, including "_") | $ 文字列の末尾に一致 | \r = キャリッジリターン | |
| \W =anything but letters ( Matches a non-alphanumeric character excluding "_") | ^ 文字列の先頭と一致する | \f= フォーム フィード | |
| 。 = 文字(ピリオド)以外のもの | | または x/y のいずれかに一致します | ----------------- | |
| \b = 改行を除く任意の文字 | [] = range or "variance" | ---------------- | |
| \. | {x} = 前述のコードの量 | ----------------- |
正規表現(RE)の構文
import re
- "re" module included with Python 主に文字列の検索と操作に使用されます
- Also used frequently for web page "スクラping" (extracウェブサイトからの大量のデータ)
式 (w+) と (^) を使用するこの簡単な演習から式チュートリアルを開始します。
w+ および ^ 式の例
- "^": この式は文字列の先頭と一致します
- "w+": This expression matches the alphanumeric character in the string
ここでは、 Python 正規表現コードでw+と^式を使用する方法の例。関数re.findall()については、 Pythonについてはこのチュートリアルの後半で説明しますが、しばらくの間は \w+ と \^ の式に焦点を当てます。
For example, for our string "guru99, education is fun" if we execute the code with w+ and^, it will give the output "guru99".
import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+",xx) print(r1)
w+ から +sign を削除すると、出力が変更され、最初の文字の最初の文字、つまり [g] のみが表示されることに注意してください。
re.split 関数の \s 式の例
- "s": This expression is used for creating a space in the string
この正規表現がどのように Python 作品を作るには、まずはシンプルな Python RegEx Example of a split function. In the example, we have split each word using the "re.split" function and at the same time we have used expression \s that allows to parse each word in the string separately.
When you execute this code it will give you the output ['we', 'are', 'splitting', 'the', 'words'].
Now, let see what happens if you remove "\" from s. There is no 's' alphabet in the output, this is because we have removed '\' from the string, and it evaluates "s" as a regular character and thus split the words wherever it finds "s" in the string.
同様に、他のシリーズもあります Python さまざまな方法で使用できる正規表現 Python \d、\D、$、\.、\b など。
これが完全なコードです
import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+", xx) print((re.split(r'\s','we are splitting the words'))) print((re.split(r's','split the words')))
次に、正規表現で使用されるメソッドの種類を見ていきます。 Python.
正規表現メソッドの使用
The "re" package provides several methods to actually perform queries on an input string. We will see the methods of re in Python:
- 再戦()
- 研究()
- re.findall()
お願い: 正規表現に基づいて、 Python 2 つの異なる基本操作を提供します。match メソッドは文字列の先頭のみの一致をチェックしますが、search メソッドは文字列内の任意の場所での一致をチェックします。
再戦()
再戦() re の機能 Python 正規表現パターンを検索し、最初の出現を返します。 Python RegEx Matchメソッドは文字列の先頭のみ一致をチェックします。したがって、最初の行に一致が見つかった場合は、一致オブジェクトを返します。しかし、他の行に一致が見つかった場合は、 Python RegEx Match 関数は null を返します。
例えば、次のコードを考えてみましょう。 Python re.match() function. The expression "w+" and "\W" will match the words starting with letter 'g' and thereafter, anything which is not started with 'g' is not identified. To check match for each element in the list or string, we run the forloop in this Python re.match() の例。
re.search(): テキスト内のパターンの検索
研究() 関数は正規表現パターンを検索し、最初の出現を返します。 Python re.match()は、入力文字列のすべての行をチェックします。 Python re.search() 関数は、パターンが見つかった場合は一致オブジェクトを返し、パターンが見つからない場合は「null」を返します。
search()の使い方は?
search()関数を使用するには、インポートする必要があります Python まずモジュールを再読み込みしてからコードを実行します。 Python re.search() function takes the "pattern" and "text" to scan from our main string
For example here we look for two literal strings "Software testing" "guru99", in a text string "Software テスト is fun". For "software testing" we found the match hence it returns the output of Python re.search() Example as "found a match", while for word "guru99" we could not found in string hence it returns the output as "No match".
re.findall()
findall() モジュールは、指定されたパターンに一致する「すべて」の出現を検索するために使用されます。対照的に、search() モジュールは、指定されたパターンに一致する最初の出現のみを返します。findall() はファイルのすべての行を反復処理し、重複しないすべての出現を返します。ping パターンを1ステップで照合します。
re.findall()の使い方 Python?
ここでは電子メールアドレスのリストがあり、リストからすべての電子メールアドレスを取得したいので、re.findall()メソッドを使用します。 Pythonリストからすべての電子メール アドレスが検索されます。
re.findall() の例の完全なコードは次のとおりです。
import re list = ["guru99 get", "guru99 give", "guru Selenium"] for element in list: z = re.match("(g\w+)\W(g\w+)", element) if z: print((z.groups())) patterns = ['software testing', 'guru99'] text = 'software testing is fun?' for pattern in patterns: print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ') if re.search(pattern, text): print('found a match!') else: print('no match') abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com' emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc) for email in emails: print(email)
Python フラグ
その他にもたくさんのグーグルの Python 正規表現メソッドと正規表現関数は、フラグと呼ばれるオプションの引数を取ります。このフラグは、指定された正規表現の意味を変更することができます。 Python 正規表現パターン。これらを理解するために、これらのフラグの例を 1 つまたは 2 つ見てみましょう。
使用されるさまざまな旗 Python 含ま
| 正規表現フラグの構文 | この旗は何をするのですか |
|---|---|
| [レム] | 各行の開始/終了を考慮する |
| [re.I] | 大文字と小文字は区別されません |
| [レス] | 作る [ 。 】 |
| [re.U] | { \w,\W,\b,\B} を Unicode ルールに従うようにします |
| [リエル] | {\w,\W,\b,\B} をロケールに従わせる |
| [re.X] | 正規表現でのコメントを許可する |
re.M または複数行フラグの例
In multiline the pattern character [^] match the first character of the string and the beginning of each line (following immediately after the each newline). While expression small "w" is used to mark the space with characters. When you run the code the first variable "k1" only prints out the character 'g' for word guru99, while when you add multiline flag, it fetches out first characters of all the elements in the string.
これがコードです
import re xx = """guru99 careerguru99 selenium""" k1 = re.findall(r"^\w", xx) k2 = re.findall(r"^\w", xx, re.MULTILINE) print(k1) print(k2)
- We declared the variable xx for string " guru99…. careerguru99….selenium"
- Run the code without using flags multiline, it gives the output only 'g' from the lines
- Run the code with flag "multiline", when you print 'k2' it gives the output as 'g', 'c' and 's'
- したがって、上の例で複数行を追加した後と追加する前の違いがわかります。
同様に、他の Python re.U (Unicode)、re.L (ロケールに従う)、re.X (コメントを許可する) などのフラグ。
Python 2例
上記のコードは Python 3つの例、実行したい場合 Python 2 次のコードを検討してください。
# Example of w+ and ^ Expression import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+",xx) print r1 # Example of \s expression in re.split function import re xx = "guru99,education ">is fun" r1 = re.findall(r"^\w+", xx) print (re.split(r'\s','we are splitting the words')) print (re.split(r's','split the words')) # Using re.findall for text import re list = ["guru99 get", "guru99 give", "guru Selenium"] for element in list: z = re.match("(g\w+)\W(g\w+)", element) if z: print(z.groups()) patterns = ['software testing', 'guru99'] text = 'software testing is fun?' for pattern in patterns: print 'Looking for "%s" in "%s" ->' % (pattern, text), if re.search(pattern, text): print 'found a match!' else: print 'no match' abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com' emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc) for email in emails: print email # Example of re.M or Multiline Flags import re xx = """guru99 careerguru99 selenium""" k1 = re.findall(r"^\w", xx) k2 = re.findall(r"^\w", xx, re.MULTILINE) print k1 print k2
あなたのテスト Python 知識
1. 文字列内のパターンのすべての出現を検索するにはどの方法を使用しますか?
- 研究()
- 再戦()
- re.findall()
- 再分割()
2. 正規表現において \d 文字クラスは何を表しますか?
- 任意の数字(0~9)
- 数字以外の文字
- 任意の空白文字
- 任意の文字または数字
3. スペースに基づいて文字列を分割するにはどの関数を使用しますか?
- re.split(r'\s', string)
- re.findall(r'\w+', string)
- re.match(r'\s+', string)
- re.split(r'\w+', string)
4. re.match() と re.search() の主な違いは何ですか?
- re.match() は文字列の先頭でパターンを検索しますが、re.search() は文字列内の任意の場所でパターンを検索します。
- re.match() はすべての一致を返しますが、re.search() は最初の一致を返します。
- re.search() は re.match() よりも高速です。
- 両方の関数は同じように動作します。








