我很困惑,在Python中返回多個組。我正則表達式是這樣的:Python正則表達式多個組
lun_q = 'Lun:\s*(\d+\s?)*'
而且我的字符串是
s = '''Lun: 0 1 2 3 295 296 297 298'''`
我返回匹配的對象,然後想看看組,但所有這表明它的最後一個數字(258):
r.groups()
(u'298',)
爲什麼不返回0,1,2,3,4
等組?
我很困惑,在Python中返回多個組。我正則表達式是這樣的:Python正則表達式多個組
lun_q = 'Lun:\s*(\d+\s?)*'
而且我的字符串是
s = '''Lun: 0 1 2 3 295 296 297 298'''`
我返回匹配的對象,然後想看看組,但所有這表明它的最後一個數字(258):
r.groups()
(u'298',)
爲什麼不返回0,1,2,3,4
等組?
你的正則表達式只包含一對括號(一個捕獲組),所以你只在你的匹配中得到一個組。如果您在捕獲組(+
或*
)上使用重複運算符,則每次重複組時都會「覆蓋」組,這意味着只捕獲最後一次匹配。
在這裏你的榜樣,你可能關閉使用.split()
更好,結合正則表達式:
lun_q = 'Lun:\s*(\d+(?:\s+\d+)*)'
s = '''Lun: 0 1 2 3 295 296 297 298'''
r = re.search(lun_q, s)
if r:
luns = r.group(1).split()
# optionally, also convert luns from strings to integers
luns = [int(lun) for lun in luns]
選擇`re.match()`vs `re.split()`是一個不重要的決定 – smci 2013-06-21 22:08:40
另一種方法是使用您必須驗證您的數據,然後使用正則表達式更具體的正則表達式針對您希望使用匹配迭代器提取的每個項目。
import re
s = '''Lun: 0 1 2 3 295 296 297 298'''
lun_validate_regex = re.compile(r'Lun:\s*((\d+)(\s\d+)*)')
match = lun_validate_regex.match(s)
if match:
token_regex = re.compile(r"\d{1,3}")
match_iterator = token_regex.finditer(match.group(1))
for token_match in match_iterator:
#do something brilliant
print re.findall('\ d',s) – 2017-09-05 14:21:34
有時,它更容易沒有正則表達式。
>>> s = '''Lun: 0 1 2 3 295 296 297 298'''
>>> if "Lun: " in s:
... items = s.replace("Lun: ","").split()
... for n in items:
... if n.isdigit():
... print n
...
0
1
2
3
295
296
297
298
如果你正在尋找一個輸出,如0,1,2,3,4等 的simples 答案如下。
打印re.findall( '\ d',S)
我想你直接引用稱爲[捕捉重複集團(http://www.regular-expressions.info/captureall .html) - 或者按照「訪問量化/重複捕獲組中的每一場比賽」的方式。看到[這個類似的答案](http://stackoverflow.com/a/3537914/611007)的JavaScript。不知道肯定,但***他們似乎不支持python的正則表達式風格***。請參閱[相關的Python增強請求](http://bugs.python.org/issue7132)和[相關問題](http://stackoverflow.com/q/15908085/611007) – n611x007 2014-04-15 12:53:26