特に関数を呼び出す場合、この関数は行の先頭から照合プロセスを開始するためre.match
、^
文字にはほとんど意味がありません。ただし、reモジュール内の他の関数や、コンパイルされた正規表現オブジェクトでmatchを呼び出す場合には意味があります。
例えば:
text = """\
Mares eat oats
and does eat oats
"""
print re.findall('^(\w+)', text, re.MULTILINE)
これは印刷します:
['Mares', 'and']
re.findall()
とを有効にするre.MULTILINE
と、テキストの各行に最初の単語(先頭に空白を入れない)が表示されます。
正規表現を使用した字句解析など、より複雑な処理を実行し、コンパイルされた正規表現に、一致を開始するテキストの開始位置(前回の一致の終了位置として選択できます)を渡す場合に役立つことがあります。 。RegexObject.matchメソッドのドキュメントを参照してください。
例としての単純なレクサー/スキャナー:
text = """\
Mares eat oats
and does eat oats
"""
pattern = r"""
(?P<firstword>^\w+)
|(?P<lastword>\w+$)
|(?P<word>\w+)
|(?P<whitespace>\s+)
|(?P<other>.)
"""
rx = re.compile(pattern, re.MULTILINE | re.VERBOSE)
def scan(text):
pos = 0
m = rx.match(text, pos)
while m:
toktype = m.lastgroup
tokvalue = m.group(toktype)
pos = m.end()
yield toktype, tokvalue
m = rx.match(text, pos)
for tok in scan(text):
print tok
印刷する
('firstword', 'Mares')
('whitespace', ' ')
('word', 'eat')
('whitespace', ' ')
('lastword', 'oats')
('whitespace', '\n')
('firstword', 'and')
('whitespace', ' ')
('word', 'does')
('whitespace', ' ')
('word', 'eat')
('whitespace', ' ')
('lastword', 'oats')
('whitespace', '\n')
これにより、単語の種類が区別されます。行の先頭にある単語、行の終わりにある単語、およびその他の単語。