Python-text-processing-python-constrained-search

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

Python-制約付き検索

多くの場合、検索結果を取得した後、既存の検索結果の一部を1レベル深く検索する必要があります。 たとえば、テキストの特定の本文では、Webアドレスを取得し、プロトコル、ドメイン名などのWebアドレスのさまざまな部分も抽出することを目指しています。 このようなシナリオでは、割り当てられた正規表現に基づいて検索結果をさまざまなグループに分割するために使用されるグループ関数を利用する必要があります。 このようなグループ式を作成するには、一致したい固定単語を除く検索可能な部分をカッコで囲んでメインの検索結果を分離します。

import re
text = "The web address is https://www.finddevguides.com"

# Taking "://" and "." to separate the groups
result = re.search('([\w.-]+)://([\w.-]+)\.([\w.-]+)', text)
if result :
    print "The main web Address: ",result.group()
    print "The protocol: ",result.group(1)
    print "The doman name: ",result.group(2)
    print "The TLD: ",result.group(3)

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

The main web Address:  https://www.finddevguides.com
The protocol:  https
The doman name:  www.finddevguides
The TLD:  com