我有這種類型的字符串:Python正則表達式的問題
s = "//name#1 un2 //name2#1 u13 //name3#3"
我怎樣才能得到字符串這些陣列:
s1 [] = "//name, //name2, name3"
s2 [] = "1, 2, 3"
我有這種類型的字符串:Python正則表達式的問題
s = "//name#1 un2 //name2#1 u13 //name3#3"
我怎樣才能得到字符串這些陣列:
s1 [] = "//name, //name2, name3"
s2 [] = "1, 2, 3"
可能您正在尋找
>>> s1=", ".join(re.findall("(//.*?)#\d+",s))
>>> s2=", ".join(re.findall("#(\d+)",s))
>>> s1
'//name, //name2, //name3'
>>> s2
'1, 1, 3'
>>>
這確實是只用一個正則表達式:
>>> s = "//name#1 un2 //name2#1 u13 //name3#3"
>>> import re
>>> x = re.findall(r"(\S+)#(\S+)", s)
>>> [s1, s2] = [', '.join(y) for y in zip(*x)]
>>> s1
'//name, //name2, //name3'
>>> s2
'1, 1, 3'
@dgh:我雖然比你好,但是:-) – Abhijit 2012-04-19 19:16:32
您的數據總是像這樣嗎? – birryree 2012-04-19 18:54:25