Python-text-processing-python-search-and-match

提供:Dev Guides
移動先:案内検索

Python-検索と一致

正規表現を使用すると、2つの基本的な操作がありますが、これらは類似しているように見えますが、大きな違いがあります。 * re.match()は、文字列の先頭でのみ一致をチェックしますが、 re.search()*は、文字列のどこでも一致をチェックします。 これは、例として感情分析のためにテキストのチャンクを取得するために正しい正規表現を頻繁に作成する必要があるため、テキスト処理で重要な役割を果たします。

import re

if  re.search("tor", "Tutorial"):
        print "1. search result found anywhere in the string"

if re.match("Tut", "Tutorial"):
         print "2. Match with beginning of string"

if not re.match("tor", "Tutorial"):
        print "3. No match with match if not beginning"



# Search as Match

if  not re.search("^tor", "Tutorial"):
        print "4. search as match"

上記のプログラムを実行すると、次の出力が得られます-

1. search result found anywhere in the string
2. Match with beginning of string
3. No match with match if not beginning
4. search as match