Python
 Computer >> コンピューター >  >> プログラミング >> Python

正規表現を使用したPythonでのパターンマッチング


正規表現とは何ですか?

現実の世界では、ほとんどのプログラミング言語での文字列解析は正規表現によって処理されます。 Pythonプログラミング言語の正規表現は、テキストパターンを照合するために使用される方法です。

すべてのPythonインストールに付属する「re」モジュールは、正規表現のサポートを提供します。

Pythonでは、正規表現検索は通常、次のように記述されます。

match = re.search(pattern, string)

re.search()メソッドは、正規表現パターンと文字列の2つの引数を取り、文字列内でそのパターンを検索します。パターンが文字列内で見つかった場合、search()は一致オブジェクトを返します。それ以外の場合はNoneを返します。したがって、正規表現では、文字列を指定して、その文字列が指定されたパターンに一致するかどうかを判断し、オプションで、関連情報を含むサブ文字列を収集します。正規表現を使用して、-

などの質問に答えることができます。
  • この文字列は有効なURLですか?

  • / etc / passwdのどのユーザーが特定のグループに属しますか?

  • ログファイル内のすべての警告メッセージの日付と時刻は何ですか?

  • 訪問者が入力したURLによって要求されたユーザー名とドキュメントは何ですか?

マッチングパターン

正規表現は複雑なミニ言語です。それらは未知の文字列と一致するために特殊文字に依存していますが、文字、数字、スペース文字など、常に一致するリテラル文字から始めましょう。基本的な例を見てみましょう:

#Need module 're' for regular expression
import re
#
search_string = "TutorialsPoint"
pattern = "Tutorials"
match = re.match(pattern, search_string)
#If-statement after search() tests if it succeeded
if match:
   print("regex matches: ", match.group())
else:
   print('pattern not found')
結果
regex matches: Tutorials

文字列のマッチング

Pythonの「re」モジュールには多数のメソッドがあり、特定の正規表現が特定の文字列と一致するかどうかをテストするには、re.search()を使用できます。 re.MatchObjectは、文字列のどの部分に一致が見つかったかなどの追加情報を提供します。

構文

matchObject = re.search(pattern, input_string, flags=0)

#Need module 're' for regular expression
import re
# Lets use a regular expression to match a date string.
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "Jan 2"):
   match = re.search(regex, "Jan 2")
   # This will print [0, 5), since it matches at the beginning and end of the
   # string
   print("Match at index %s, %s" % (match.start(), match.end()))
   # The groups contain the matched values. In particular:
   # match.group(0) always returns the fully matched string
   # match.group(1), match.group(2), ... will return the capture
   # groups in order from left to right in the input string  
   # match.group() is equivalent to match.group(0)
   # So this will print "Jan 2"
   print("Full match: %s" % (match.group(0)))
   # So this will print "Jan"
   print("Month: %s" % (match.group(1)))
   # So this will print "2"
   print("Day: %s" % (match.group(2)))
else:
   # If re.search() does not match, then None is returned
   print("Pattern not Found! ")

結果

Match at index 0, 5
Full match: Jan 2
Month: Jan
Day: 2

上記の方法は最初の一致後に停止するため、データを抽出するよりも正規表現をテストするのに適しています。

グループのキャプチャ

パターンに2つ以上の括弧が含まれている場合、最終結果は、括弧()グループメカニズムとfinall()の助けを借りて、文字列のリストではなくタプルになります。一致する各パターンはタプルで表され、各タプルにはgroup(1)、group(2)..データが含まれます。

import re
regex = r'([\w\.-]+)@([\w\.-]+)'
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com')
matches = re.findall(regex, str)
print(matches)
for tuple in matches:
   print("Username: ",tuple[0]) #username
   print("Host: ",tuple[1]) #host

結果

[('john', 'hotmail.com'), ('hello', 'Tutorialspoint.com'), ('python', 'gmail.com')]
Username: john
Host: hotmail.com
Username: hello
Host: Tutorialspoint.com
Username: python
Host: gmail.com

文字列の検索と置換

もう1つの一般的なタスクは、指定された文字列内のパターンのすべてのインスタンスを検索してそれらを置き換えることです。re.sub(pattern、replacement、string)はそれを正確に実行します。たとえば、古いメールドメインのすべてのインスタンスを置き換える

コード

# requid library
import re
#given string
str = ('hello john@hotmail.com, hello@Tutorialspoint.com, hello python@gmail.com, Hello World!')
#pattern to match
pattern = r'([\w\.-]+)@([\w\.-]+)'
#replace the matched pattern from string with,
replace = r'\1@XYZ.com'
   ## re.sub(pat, replacement, str) -- returns new string with all replacements,
   ## \1 is group(1), \2 group(2) in the replacement
print (re.sub(pattern, replace, str))

結果

hello john@XYZ.com, hello@XYZ.com, hello python@XYZ.com, Hello World!

Reオプションフラグ

上記のようなPython正規表現では、さまざまなオプションを使用して、パターン一致の動作を変更できます。これらの追加の引数、オプションのフラグは、search()またはfindall()などの関数に追加されます(例:re.search(pattern、string、re.IGNORECASE))。

  • IGNORECASE-

    名前が示すように、パターンの大文字と小文字は区別されません(大文字/小文字)。これにより、「a」と「A」を含む文字列が両方とも一致します。

  • ドット

    re.DOTALLを使用すると、dot(。)メタ文字を改行(\ n)を含むすべての文字と一致させることができます。

  • マルチライン

    re.MULTILINEを使用すると、文字列の各行のstart(^)とend($)を一致させることができます。ただし、通常、^と&は文字列全体の開始と終了に一致します。


  1. Pythonでパターンを印刷する方法は?

    Pythonのパターンは、ネストされたforループを使用して印刷できます。外側のループは行数を反復処理するために使用され、内側のループは列数を処理するために使用されます。印刷ステートメントは、要件に応じてさまざまなパターンを形成するように変更されます。 パターンには、星型、数字型、アルファベット型があります。パターンは、さまざまな形、三角形、ピラミッドなどにすることができます。 例 これらのパターンはすべて、これらの異なるパターンを形成する変更されたprintステートメントを含むforループを使用して印刷できます。 これらのパターンの印刷の基本的な考え方は同じですが、わずかな違いが

  2. Pythonの葉序パターン?

    葉序パターンとは何ですか? 戻ってみると、植物学のクラスや植物の世界では、葉序とは、フィボナッチスパイラルに見られるものと同様に、植物の茎に花、葉、または種子を配置することを意味します。フィボナッチ数列に基づくフィボナッチスパイラルは、パスカルの三角形に似たパターンに従う数字のセットです。フィボナッチ数列は-1、1、2、3、5、8、13、21、34、55、89、144などのようなものです。したがって、フィボナッチ数列は以前の数の合計です。 フィボナッチスパイラル 私たちは通常、私たちの周りのオブジェクトを理解するために対称性とパターンを探します。気付かないうちに、私たちの目はフィボナッチ数