![](/img/trans.png)
[英]Extract all strings in between between all same pairs of the two string using regex or python functions
[英]Python regex extract a string between two strings
我有一個字符串顯示為
text = "isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail"
我需要提取顯示值的字符串,即 qasde%。 我正在使用 Python 腳本
我試過的是
text = text.split('value', 1)[1]
text = text.split('client',1)[0]
它給了我正確的價值,但是有什么簡單的方法可以實現嗎?
https://regex101.com/r/u9gpm5/2
import re
text = 'isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail'
m = re.search('value=(.+?) , client=', text)
if m:
found = m.group(1)
您沒有提供足夠的信息來完全回答這個問題。 價值總是出現在客戶面前嗎? 它總是出現在時間和日期之后嗎?
無論如何 - 如果值總是出現在日期和時間之后以及客戶之前,那么這個答案或Quicksilver 的答案應該可以工作。
但是,您可能還只想搜索value=
和 , 之前出現的任何內容,
在這種情況下,這應該可以工作: https://regex101.com/r/a4d7Bx/1
import re
text = 'isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail'
m = re.search('value=(.+?) ,', text)
if m:
found = m.group(1)
print(found)
通過稍微編輯您的代碼來做到這一點的另一種方法:
text = 'isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail'
text = text.split('value=', 1)[1]
text = text.split(' , client',1)[0]
print(text)
您要求更簡單的方法。 可以說,這兩種方法都非常簡單,所以我會選擇更快的方法(除非您想要更通用的解決方案,在這種情況下使用第一個選項)。 我使用以下代碼對它們進行計時:
import re
import cProfile
text = 'isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail'
def option1(text):
for i in range(10000):
re.search('value=(.+?) ,', text)
def option2(text):
for i in range(10000):
temp = text.split('value=', 1)[1]
temp = temp.split(' , client',1)[0]
cProfile.run("option1(text)")
print("\n\n\n\n\n")
cProfile.run("option2(text)")
第一個選項花費了 0.076 秒,而第二個選項花費了 0.027 秒,因此更快的選項是使用split
。
這個表達式可能會簡單地返回:
import re
expression = r'(?:value|client)\s*=\s*([^,\r\n]*?)(?=\s*,|$)'
string = """
isLogIn=true; Max-Age=400; Path=/; Expires=Wed, 25 Sep 2019 17:46:30 GMT, value=qasde% , client=retail
"""
print(re.findall(expression, string, re.M))
['qasde%', 'retail']
如果您希望簡化/修改/探索表達式,它已在regex101.com的右上角面板中進行了說明。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。
jex.im可視化正則表達式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.