python reのfindallとfinditter
(-本稿は個人学習と使用過程の総括であり、誤りがあれば指摘を歓迎する)python正規モジュールreではfindallとfinditterの両者は似ているが、大きな違いがある.どちらもすべてのマッチング結果を得ることができ,これはsearchメソッドと大きく異なると同時にlistを返し,MatchObjectタイプのiteratorを返す.
数字は電話番号を表し、xxはメールボックスのタイプを表すデータがあるとします.
需要:(グループ化されていない)すべてのメールボックス情報を抽出
需要:(正則的にグループ化されている)すべての電話番号とメールボックスタイプを抽出します.
名前付きグループと非名前付きグループの場合は同じです.
findall注意点:1.正則にパケットがない場合は正則のマッチングが返されます
2.あるパケットは、正則全体のマッチングではなく、パケットのマッチングを返す
3.複数パケットの場合はtupleにパケットを入れて戻る
したがって、正則全体と各パケットのマッチングが必要な場合は、findallを使用して正則全体をパケットとして使用する必要があります.
finditterを使用すると、正規全体を手動で()で囲むgroup()で正規全体のマッチングを表す必要はありません.
実際には、私たちのニーズに合わせて方法を選択することができます.
数字は電話番号を表し、xxはメールボックスのタイプを表すデータがあるとします.
content = '''email:[email protected]
email:[email protected]
email:[email protected]
'''
需要:(グループ化されていない)すべてのメールボックス情報を抽出
result_finditer = re.finditer(r"\d+@\w+.com", content)
# MatchObject iterator, MatchObject
for i in result_finditer :
print i.group()
result_findall = re.findall(r"\d+@\w+.com", content)
# [] or
print result_findall
for i in result_findall :
print i
需要:(正則的にグループ化されている)すべての電話番号とメールボックスタイプを抽出します.
result_finditer = re.finditer(r"(\d+)@(\w+).com", content)
# , , 0 ,group 0,
for i in result_finditer :
phone_no = i.group(1)
email_type = i.group(2)
result_findall = re.findall(r"(\d+)@(\w+).com", content)
# [], [], tuple list
# :[('12345678', '163'), ('2345678', '163'), ('345678', '163')]
for i in result_findall :
phone_no = i[0]
email_type = i[1]
名前付きグループと非名前付きグループの場合は同じです.
findall注意点:1.正則にパケットがない場合は正則のマッチングが返されます
re.findall(r"\d+@\w+.com", content)
['[email protected]', '[email protected]', '[email protected]']
2.あるパケットは、正則全体のマッチングではなく、パケットのマッチングを返す
re.findall(r"(\d+)@\w+.com", content)
['2345678', '2345678', '345678']
3.複数パケットの場合はtupleにパケットを入れて戻る
re.findall(r"(\d+)@(\w+).com", content)
[('2345678', '163'), ('2345678', '163'), ('345678', '163')]
したがって、正則全体と各パケットのマッチングが必要な場合は、findallを使用して正則全体をパケットとして使用する必要があります.
re.findall(r"((\d+)@(\w+).com)", content)
[('[email protected]', '2345678', '163'), ('[email protected]', '2345678', '163'), ('[email protected]', '345678', '163')]
finditterを使用すると、正規全体を手動で()で囲むgroup()で正規全体のマッチングを表す必要はありません.
実際には、私たちのニーズに合わせて方法を選択することができます.