ホームページ  >  記事  >  バックエンド開発  >  Python の正規表現で各一致の正確な位置を見つけるにはどうすればよいでしょうか?

Python の正規表現で各一致の正確な位置を見つけるにはどうすればよいでしょうか?

王林
王林転載
2023-08-31 12:13:34642ブラウズ

Python の正規表現で各一致の正確な位置を見つけるにはどうすればよいでしょうか?

はじめに

re モジュールは、Python で使用する正規表現です。正規表現は、テキスト検索やより複雑なテキスト操作に使用されます。 grep や sed などのツール、vi や emacs などのテキスト エディター、Tcl、Perl、Python などのコンピューター言語にはすべて正規表現サポートが組み込まれています。

Python の re モジュールは、正規表現を照合するための関数を提供します。

検索または変更するテキストを定義する正規表現はパターンと呼ばれます。テキスト リテラルとメタキャラクターがこの文字列を構成します。コンパイルされた関数はスキーマの作成に使用されます。正規表現には特殊文字が含まれることが多いため、生の文字列を使用することをお勧めします。 (r 文字は、生の文字列を示すために使用されます。) これらの文字は、パターンに結合されるまで解釈されません。

これらの関数のいずれかを使用してパターンをテキスト文字列に適用でき、そのパターンはアセンブリの完了後に使用されます。使用可能な関数には、Match、Search、Find、および Finditer が含まれます。

使用される構文

ここで使用される正規表現関数は次のとおりです。 正規表現関数を使用して一致を検索します。

re.match(): Determines if the RE matches at the beginning of the string. If zero or more characters at the beginning of the string match the regular expression pattern, the match method returns a match object.

p.finditer(): Finds all substrings where the RE matches and returns them as an iterator. An iterator delivering match objects across all non-overlapping matches for the pattern in a string is the result of the finditer method.

re.compile(): Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search(), and other methods described below. The expression’s behavior can be modified by specifying a flag's value. Values can be any of the following variables combined using bitwise OR (the | operator).

m.start(): m.start() returns the offset in the string at the match's start.

m.group(): You may use the multiple-assignment approach to assign each value to a different variable when mo.groups() returns a tuple of values, as in the areaCode, mainNumber = mo.groups() line below.

search: It is comparable to re.match() but does not require that we just look for matches at the beginning of the text. The search() function can locate a pattern in the string at any location, but it only returns the first instance of the pattern.

アルゴリズム

  • import reを使用して正規表現モジュールをインポートします。

  • re.compile() 関数を使用して、正規表現オブジェクトを作成します。 (必ず元の文字列を使用してください。)

  • 検索する文字列を Regex オブジェクトの finditer() メソッドに渡します。これにより、Match オブジェクトが返されます。

  • Match オブジェクトの group() メソッドを呼び出すと、実際に一致したテキスト文字列が返されます。

  • span() メソッドを使用して、タプル内の開始インデックスと終了インデックスを取得することもできます。

 #importing re functions
import re
#compiling [A-Z0-9] and storing it in a variable p
p = re.compile("[A-Z0-9]")
#looping m times in p.finditer
for m in p.finditer('A5B6C7D8'):
#printing the m.start and m.group
   print m.start(), m.group()

出力

これにより、出力が生成されます -

0 A
1 5
2 B
3 6
4 C
5 7
6 D
7 8

コードの説明

インポートを使用しますre 正規表現モジュールをインポートします。 re.compile() 関数を使用して正規表現オブジェクト ("[A-Z0-9]") を作成し、それを変数 p に割り当てます。ループを使用して m を繰り返し、検索する文字列を正規表現オブジェクトの finditer() メソッドに渡します。これにより、Match オブジェクトが返されます。 Match オブジェクトの m.group() メソッドと m.start() メソッドを呼び出して、実際にテキストと一致した文字列を返します。

# Python program to illustrate
# Matching regex objects
# with groups
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242.')
print(mo.groups())

出力

これにより、出力が生成されます -

('415', '555-4242')

コードの説明

import reを使用して正規表現をインポートしますモジュール。 re.compile() 関数を使用して正規表現オブジェクト (r'(\d\d\d)-(\d\d\d-\d\d\d\d)') を作成し、それを変数に割り当てます。 PhoneNumRegex。検索する文字列を Regex オブジェクトの search() メソッドに渡し、変数 mo に格納します。これにより、Match オブジェクトが返されます。実際に一致したテキスト文字列を返すには、Match オブジェクトの mo.groups() メソッドを呼び出します。

結論

Python re モジュールによって提供される search()、match()、および finditer() メソッドを使用すると、正規表現パターンを照合できます。照合が成功すると、次の結果が得られます。 Match オブジェクトのインスタンス。この Match オブジェクトの start()、end()、および scan() メソッドを使用して、一致した文字列に関する詳細情報を取得します。

一致するものが多数ある場合、findall() を使用してそれらをすべてロードすると、メモリがオーバーロードする危険性があります。 finditer() メソッドを使用すると、一致する可能性のあるすべての反復子オブジェクトを取得でき、効率が向上します。

これは、 finditer() が、呼び出されると結果をメモリにロードする呼び出し可能オブジェクトを提供することを意味します。

以上がPython の正規表現で各一致の正確な位置を見つけるにはどうすればよいでしょうか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。