簡體   English   中英

使用正則表達式在python中拆分字符串

[英]using regular expression to split string in python

我用

re.compile(r"(.+?)\\1+").findall('44442(2)2(2)44')

可以得到

['4','2(2)','4']

,但我怎么能得到

['4444','2(2)2(2)','44']

通過使用正則表達式?

謝謝

無需更改您的模式。 只需要使用正確的功能來完成工作。 如果模式中有捕獲組, re.findall將返回組列表。 要獲得整個匹配,請改用re.finditer ,以便從每個實際匹配對象中提取完整匹配

pattern = re.compile(r"(.+?)\1+")
[match.group(0) for match in pattern.finditer('44442(2)2(2)44')]

對OP的正則表達式進行最小的更改:

[m[0] for m in re.compile(r"((.+?)\2+)").findall('44442(2)2(2)44')]

如果沒有組, findall將為您提供完全匹配,如果有組,則為find。 因此,如果您需要用於正則表達式的組,我們只需添加另一個組來包含完整匹配,然后將其提取出來。

你可以做:

[i[0] for i in re.findall(r'((\d)(?:[()]*\2*[()]*)*)', s)]

這里的正則表達式是:

((\d)(?:[()]*\2*[()]*)*)

這將輸出一個包含兩個捕獲組的元組列表,我們只對第一個感興趣,因此i[0]

例:

In [15]: s
Out[15]: '44442(2)2(2)44'

In [16]: [i[0] for i in re.findall(r'((\d)(?:[()]*\2*[()]*)*)', s)]
Out[16]: ['4444', '2(2)2(2)', '44']

暫無
暫無

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

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