2016-07-07 38 views
-6

我想在Python中使用正則表達式來獲取文本的某些部分。從文本中我需要採取這種子字符串'2016-049172'。那麼等價的正則表達式是什麼? 非常感謝。如何取整數正則表達式?

這裏有一段代碼:

import re 

pattern = re.compile(r"\s-\s[0-9]+[0-9]$]") 
my_string = 'Ticketing TSX - 2016-049172' 

matches = re.findall(pattern,my_string) 
print matches 

當然,我的輸出是空列表。 (我初次壞後道歉,我是新)

+1

可用請添加1)實施例的輸入; 2)期望的輸出; 3)你試過了什麼。 – dawg

+1

*您是否嘗試使用正則表達式?你的嘗試在哪裏?你讀過關於正則表達式語法的各種教程嗎?它總是會變成四位數字,然後是六位數字? – jonrsharpe

+1

查看http://www.regex101.com它可以幫助您通過正則表達式瞭解更多關於它的信息。 –

回答

1

正如其他人發佈的那樣,您正在尋找的正則表達式是:

\d{4}-\d{6} 

Full co德我會用:

import re 

my_string = 'Ticketing TSX - 2016-049172' 
matches = re.findall(r"\d{4}-\d{6}", my_string) 

print matches 

如果,例如,第二位的長度從6至8位數字各不相同,你需要更新你的正則表達式這一點。

\d{4}-\d{6,8} 

所有的正則表達式左右的細節和在Python使用正則表達式是在docs

1

使用正則表達式是這樣的:

\d{4}-\d{6} 

更新您的示例代碼,這會爲你做它:

import re 

pattern = re.compile(r"\d{4}-\d{6}") 
my_string = 'Ticketing TSX - 2016-049172' 

matches = re.findall(pattern,my_string) 
print matches