簡體   English   中英

如何使用正則表達式在python中檢索數據?

[英]How to use regular expression to retrieve data in python?

我有一個字符串定義為,

content = "f(1, 4, 'red', '/color/down1.html');    
f(2, 5, 'green', '/color/colorpanel/down2.html');    
f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"

這是我嘗試過但不起作用的代碼:

results = re.findall(r"f(.*?)", content)
for each in results:
    print each

如何使用正則表達式來檢索內容中的鏈接? 謝謝。

您可以在https://regex101.com/http://regexr.com/上學習基本的正則表達式

In [4]: import re

In [5]: content = "f(1, 4, 'red', '/color/down1.html');    \
   ...: f(2, 5, 'green', '/color/colorpanel/down2.html');   \
   ...: f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"

In [6]: p = re.compile(r'(?=/).*?(?<=.html)')

In [7]: p.findall(content)
Out[7]: 
['/color/down1.html',
 '/color/colorpanel/down2.html',
 '/color/colorpanel/colorlibrary/down3.html']

.*? 匹配任何字符(除了行

*? 量詞——匹配零次和無限次,盡可能少,按需擴展(懶惰)

你也可以只得到最后一個/

In [8]: p2 = re.compile(r'[^/]*.html')

In [9]: p2.findall(content)
Out[9]: ['down1.html', 'down2.html', 'down3.html']

[^/]*匹配下面列表中不存在的單個字符

* 量詞——在零次和無限次之間匹配,盡可能多次,根據需要回饋(貪婪)

/匹配字符 / 字面意思(區分大小寫)

. 匹配任何字符(行終止符除外) html 按字面意思匹配字符 html(區分大小寫)。

或者,您可以提取f()所有數據

In [15]: p3 = re.compile(r"(?=f\().*?(?<=\);)")

In [16]: p3.findall(content)
Out[16]: 
["f(1, 4, 'red', '/color/down1.html');",
 "f(2, 5, 'green', '/color/colorpanel/down2.html');",
 "f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"]

你可以這樣做:

re.findall(r"f\(.*,.*,.*, '(.*)'", content)

你可以這樣嘗試:

import re

content = """f(1, 4, 'red', '/color/down1.html');    
    f(2, 5, 'green', '/color/colorpanel/down2.html');    
    f(3, 6, 'blue', '/color/colorpanel/colorlibrary/down3.html');"""

print re.findall(r"(\/[^']+?)'", content)

輸出:

['/color/down1.html', '/color/colorpanel/down2.html', '/color/colorpanel/colorlibrary/down3.html']  

正則表達式:

(\\/[^']+?)' - 匹配/后跟 1 個或多個非'字符,直到第一次出現'並在 group1 中捕獲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM