我需要使用Python解析一個字符串,並提取由:
(冒號)分隔的2個令牌,可以用單引號,雙引號或無引號括起來。正則表達式貪婪問題
樣品的情況下工作:
# <input string> -> <tuple that should return>
1) abc:def -> (abc, def)
2) abc:"def" -> (abc, def)
3) "abc":def -> (abc, def)
4) "abc":"def" -> (abc, def)
5) "a:bc":abc -> (a:bc, abc)
樣品的情況下不工作:使用
# <input string> -> <tuple that should return>
6) abc:"a:bc" -> (abc, a:bc)
7) "abcdef" -> (abcdef,)
正則表達式是:
>>> import re
>>> rex = re.compile(r"(?P<fquote>[\'\"]?)"
r"(?P<user>.+)"
r"(?P=fquote)"
r"(?:\:"
r"(?P<squote>[\'\"]?)"
r"(?P<pass>.+)"
r"(?P=squote))")
我有兩個問題,第一個樣本案例6)和7)不工作,第二個rex.match
後,我想所有組匹配,但不是fquote
和squote
個。我的意思是現在rex.match("'abc':'def').groups()
返回("'", "abc", "'", "def")
,我只想("abc", "def")
。
任何想法?
感謝
它並不單引號和雙引號混合使用。例如:s ='\'abc \':「a:bc」' – user1595496 2013-03-11 16:23:58
@ user1595496 Ahh - 沒有發現您正在尋找的正則表達式中的任一個或者......只是以您的示例數據爲例) – 2013-03-11 16:25:31
我只想一個正則表達式,而不是使用外部模塊,但無論如何感謝。 – user1595496 2013-03-11 16:30:01