亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

貪婪和懶惰量詞。使用 HTML 標簽進行測試

貪婪和懶惰量詞。使用 HTML 標簽進行測試

達令說 2023-10-10 10:35:00
輸入是<p>The very <em>first</em> task is to find the beginning of a paragraph.</p><p>Then you have to find the end of the paragraph</p>預期的第一個輸出是(因為我使用貪婪量詞)<p>The very <em>first</em> task is to find the beginning of a paragraph.</p><p>Then you have to find the end of the paragraph</p>用于貪婪的代碼如下text = '''<p>The very <em>first</em> task is to find the beginning of a paragraph.</p><p>Then you have to find the end of the paragraph</p>'''pattern=re.compile(r'\<p\>.*\<\/p\>')data1=pattern.match(text,re.MULTILINE)print('data1:- ',data1,'\n')預期的第二個輸出是(因為我使用的是惰性量詞)<p>The very <em>first</em> task is to find the beginning of a paragraph.</p>用于懶惰的代碼如下text = '''<p>The very <em>first</em> task is to find the beginning of a paragraph.</p><p>Then you have to find the end of the paragraph</p>'''#pattern=re.compile(r'\<p\>.*?\<\/p\>')pattern=re.compile(r'<p>.*?</p>')data1=pattern.match(text,re.MULTILINE)print('data1:- ',data1,'\n')我得到的實際輸出都是 None
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

你有幾個問題。首先,使用 時Pattern.match,第二個和第三個參數是位置參數,而不是標志。需要將標志指定為re.compile。其次,您應該使用re.DOTALL.匹配換行符,而不是re.MULTILINE.?最后 -match堅持匹配發生在字符串的開頭(在您的情況下是換行符),因此它不會匹配。您可能想改用Pattern.search。這適用于您的示例輸入:


pattern=re.compile(r'<p>.*</p>', re.DOTALL)

data1=pattern.search(text)

print('data1:- ',data1.group(0),'\n')

輸出:


data1:-? <p>

The very <em>first</em> task is to find the beginning of a paragraph.

</p>

<p>

Then you have to find the end of the paragraph

</p>?

單場比賽:


pattern=re.compile(r'<p>.*?</p>', re.DOTALL)

data1=pattern.search(text)

print('data1:- ',data1.group(0),'\n')

輸出:


data1:-? <p>

The very <em>first</em> task is to find the beginning of a paragraph.

</p>?

另請注意/, ,<和>在正則表達式中沒有特殊含義,不需要轉義。我已經在上面的代碼中刪除了它。


查看完整回答
反對 回復 2023-10-10
  • 1 回答
  • 0 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號