2017-04-05 6 views
0

ここでは、非貪欲なマッチングについての例を見ました。
python regex non-greedy forced

reg_string = "(.*?)>Title" 
path = "<html><head><title>Title</title>" 
match = re.match(reg_string, path) 
if match: 
    print match.group() 

しかし、どのような場合、私は最初の>後に何Titleではありませんので、これは、一致していないことを叫ぶするのpythonにしたいです。

"<html\><head><title>Title" 

答えて

0

は、私が理解したようreg_string = "([^>]*?)>Title"

+0

素晴らしい作品です!ありがとうございました –

+0

@エジジェードあなたの質問に答えた場合、この回答を正しいとマークしてください。 – xlm

0

をお試しくださいあなた、あなたはタイトルの前にすべてを取りたいです。タイトルテキストがない場合は、それは文句を言う必要がありますか?

# Here we add a zero-to-many length match, delimited by `<` or end of line 
# and capture it in a second group 
reg_string = "(.*?)>(.*?)(<|$)" 

path = "<html><head><title>Title</title>" 

match = re.match(reg_string, path) 
if match: 
    if match.group(2) == "": 
     throw Exception("No title content") 
    else 
     print match.group(1) 
else: 
    throw Exception("No match") 
+0

「タイトル」が最初の「>」の後でないときは、文句を言います。 –

+0

次に、あなたの主要な例が機能します。 "else"句を追加するか、 'not if match:'を実行するだけです – taifwa