[英]Python Multiple regex Patterns string reassignment using re.sub
[英]Grabbing multiple patterns in a string using regex
在python中,我試圖使用正則表達式從字符串中獲取多個輸入; 但是,我遇到了麻煩。 對於字符串:
inputs = 12 1 345 543 2
我嘗試使用:
match = re.match(r'\s*inputs\s*=(\s*\d+)+',string)
但是,這僅返回值'2'
。 我正在嘗試捕獲所有值'12','1','345','543','2'
但不確定如何執行此操作。
任何幫助是極大的贊賞!
編輯:謝謝大家解釋為什么這是行不通的,並提供了替代建議。 抱歉,這是重復問題。
您可以嘗試類似: re.findall("\\d+", your_string)
。
您不能使用單個正則表達式來執行此操作(除非您使用的是.NET),因為每個捕獲組即使重復,也只會返回一個結果(在Python中為最后一個)。
由於也不可能進行變長后向查找(在這種情況下,您可以這樣做(?<=inputs.*=.*)\\d+
),因此您必須將其分為兩個步驟:
match = re.match(r'\s*inputs\s*=\s*(\d+(?:\s*\d+)+)', string)
integers = re.split(r'\s+',match.group(1))
因此,現在您捕獲整數的整個列表(以及它們之間的空格),然后在該空格處拆分該捕獲。
第二步也可以使用findall
完成:
integers = re.findall(r'\d+',match.group(1))
結果是相同的。
您可以嵌入正則表達式:
import re
s = 'inputs = 12 1 345 543 2'
print re.findall(r'(\d+)', re.match(r'inputs\s*=\s*([\s\d]+)', s).group(1))
>>>
['12', '1', '345', '543', '2']
或者分層進行:
import re
def get_inputs(s, regex=r'inputs\s*=\s*([\s\d]+)'):
match = re.match(regex, s)
if not match:
return False # or raise an exception - whatever you want
else:
return re.findall(r'(\d+)', match.group(1))
s = 'inputs = 12 1 345 543 2'
print get_inputs(s)
>>>
['12', '1', '345', '543', '2']
您應該查看以下答案: https : //stackoverflow.com/a/4651893/1129561
簡而言之:
在Python中,用單個正則表達式是不可能的:組的每次捕獲都將覆蓋同一組的最后一次捕獲(在.NET中,由於引擎區分捕獲和組,因此這實際上是可能的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.