logo

Python 正規表現: re.search() VS re.findall()

前提条件: 正規表現と例 |パイソン

Java乱数

正規表現 (有理式とも呼ばれる) は、検索パターンを定義する一連の文字であり、主に文字列とのパターン マッチングや文字列マッチング、つまり検索と置換に似た操作で使用されます。正規表現は、パターンと一連の文字を照合する一般的な方法です。



モジュール 正規表現 (RE) 一致する文字列 (パターン) のセットを指定します。 RE のアナロジーを理解するには、次のようにします。MetaCharacters>便利で重要であり、モジュールの関数で使用されますre>

合計 14 個のメタキャラクターがあり、それらのメタキャラクターが関数に続く中で説明します。

  Used to drop the special meaning of character following it (discussed below) [] Represent a character class ^ Matches the beginning $ Matches the end . Matches any character except newline ? Matches zero or one occurrence. | Means OR (Matches with any of the characters separated by it. * Any number of occurrences (including 0 occurrences) + One or more occurrences {} Indicate number of occurrences of a preceding RE to match. () Enclose a group of REs>

研究()

re.search()>メソッドは None (パターンが一致しない場合) を返すか、re.MatchObject>これには、文字列の一致する部分に関する情報が含まれます。このメソッドは最初の一致後に停止するため、データの抽出よりも正規表現のテストに最適です。



例:

Python3




文字列検索 - C++



# A Python program to demonstrate working of re.match().> import> re> > # Lets use a regular expression to match a date string> # in the form of Month name followed by day number> regex>=> r>'([a-zA-Z]+) (d+)'> > match>=> re.search(regex,>'I was born on June 24'>)> > if> match !>=> None>:> > ># We reach here when the expression '([a-zA-Z]+) (d+)'> ># matches the date string.> > ># This will print [14, 21), since it matches at index 14> ># and ends at 21.> >print>(>'Match at index % s, % s'> %> (match.start(), match.end()))> > ># We us group() method to get all the matches and> ># captured groups. The groups contain the matched values.> ># In particular:> ># match.group(0) always returns the fully matched string> ># match.group(1) match.group(2), ... 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 'June 24'> >print>(>'Full match: % s'> %> (match.group(>0>)))> > ># So this will print 'June'> >print>(>'Month: % s'> %> (match.group(>1>)))> > ># So this will print '24'> >print>(>'Day: % s'> %> (match.group(>2>)))> > else>:> >print>(>'The regex pattern does not match.'>)>

>

>

出力:

 Match at index 14, 21 Full match: June 24 Month: June Day: 24>

re.findall()

文字列内のパターンの重複しない一致をすべて文字列のリストとして返します。文字列は左から右にスキャンされ、見つかった順序で一致が返されます。

例:

Python3


Pythonプログラムリスト



# A Python program to demonstrate working of> # findall()> import> re> > # A sample text string where regular expression> # is searched.> string>=> '''Hello my Number is 123456789 and> >my friend's number is 987654321'''> > # A sample regular expression to find digits.> regex>=> 'd+'> > match>=> re.findall(regex, string)> print>(match)>

>

文字列の整数

>

出力:

 ['123456789', '987654321']>