好吧,我誤解你的問題在第一。雖然str.split
絕對是解決這個問題的更優雅的方法,但下面是三個正則表達式,以滿足您的需求。我不知道你的這個應用程序是否會與他們合作。所以拿一點鹽來吧。
請查看re圖書館和MatchObject.span()瞭解更多信息。
作爲一個單一的正則表達式:
import re
line = "cannon_mac_23567_prsln_333"
In [1812]: match = re.match(r"(.+?)(\_)(.+?)\_", line)
In [1813]: match.groups()
Out[1813]: ('cannon', '_', 'mac')
In [1814]: match.span(2)[0] <-- second group, start. The first occurence of _
Out[1814]: 6
In [1815]: line[6]
Out[1815]: '_'
Seprated在A,B,C:
一個:
import re
line = "cannon_mac_23567_prsln_333"
In [1707]: match = re.match(r"(.+?)\_", line)
In [1708]: match.groups()
Out[1708]: ('cannon',)
B:
In [1712]: match = re.match(r".+\_(.+?)\_", line)
In [1713]: match.groups()
Out[1713]: ('prsln',)
C:最後一個使用re.search來簡化。MatchObject.span()
回報的位置(start, end)
In [1763]: match = re.search("\_", line)
In [1764]: match.span()[0]
Out[1764]: 6
In [1765]: line[6]
Out[1765]: '_'
你應該告訴你已經嘗試過什麼每個部分的元組。你的嘗試沒有成功? – askewchan 2013-03-06 20:59:59
更新了我的答案,應該做你想要的。 – msvalkon 2013-03-06 22:02:27