2014-09-25 312 views
-1

如何匹配水平製表符以外的任何字符?我想要捕獲的組是以':'開頭的字符,然後是'\ t'。Python正則表達式匹配除標籤外的所有字符

regex = re.compile(r'^p:([^\t]*)\t') 
line = 'p:452c942b93\tperson\tSimon Sturridge' 
if regex.match(line): 
    print 'MATCH' 

謝謝。

編輯:我想匹配這種格式的字符串'p:'+'隨機數字和字母'+'\ t'
並捕獲':'後面的隨機數字和字母,\'t 」。我對缺乏簡潔表示歉意。

+1

你能提供樣品的輸入和預期的輸出,而你實際上得到什麼輸出? – 2014-09-25 21:29:04

+0

相關:[正則表達式匹配除了給定的正則表達式的一切](http://stackoverflow.com/questions/1781554/regular-expression-matching-everything-except-a-given-regular-expression)[匹配除了一個字母 - 正則表達式](http://stackoverflow.com/questions/15348457/matching-anything-but-a-letter-regex) – Celeo 2014-09-25 21:32:33

+0

你提供的代碼*在2.7和3.4上都是匹配的。 – Veedrac 2014-09-25 21:42:51

回答

0

從你所描述的,我會說:

pattern = re.compile(r'^p:(\w*)\t') 
foo = re.match(pattern, line) 
if foo: 
    print 'MATCH' 

測試:

>>> foo.groups() 
('452c942b93',) 
>>>foo.group(1) 
'452c942b93' 
+0

謝謝,有沒有一種方法可以匹配除\ t之外的所有字符?爲此目的[^ \ t]是否正確? – pseudomarvin 2014-09-25 21:43:30

+0

我相信這是你需要的,對吧? – 2014-09-25 22:03:25