[英]Python - Using Regex to find multiple matches and report in a certain order
[英]Python - Using regex to find multiple matches and print them out
我需要從HTML源文件中找到表單的內容,我做了一些搜索並找到了很好的方法來做到這一點,但問題是它只打印出第一個找到的,我怎么能循環它並輸出所有的表單內容,而不是只是第一個?
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matchObj = re.search('<form>(.*?)</form>', line, re.S)
print matchObj.group(1)
# Output: Form 1
# I need it to output every form content he found, not just first one...
但是如果你需要在字符串中找到所有regexp匹配項,請使用findall
函數。
import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)
# Output: ['Form 1', 'Form 2']
而不是使用re.search
使用re.findall
它將返回List
所有匹配。 或者您也可以使用re.finditer
(我最喜歡使用它)它將返回一個Iterator Object
,您可以使用它來迭代所有找到的匹配。
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
print match.group(1)
為此目的使用正則表達式是錯誤的方法。 由於您使用的是python,因此您可以使用非常棒的庫從HTML文檔中提取部件: BeautifulSoup 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.