2016-06-08 20 views
0

我想檢測我的文本文件「1-321231」這種形式,我的意思是任何數字,加上「 - 」,加上任何數字, 我寫這個正則表達式:如何處理python中的正則表達式?

\d[-]\d* 

但我不」不知道如何在python中使用它。

+9

這是're'模塊的文檔r:HTTPS:/ /docs.python.org/2/library/re.html –

+1

@ K.Menyah謝謝 – parik

+2

你不需要角色類。 '\ d- \ d +'應該足夠了。 – Matthias

回答

3

「檢測」就是我們所說的「匹配」。 下面是如何使用它的工作示例:

import re 
string = '1-321231' 
pattern = '\d[-]\d*' 
match = re.search(pattern, string) 
if match: 
    print 'we\'ve got a match!' 
2

像Menyah的評論所說,瀏覽在https://docs.python.org/3.6/library/re.html

比較全面的文檔作爲一個快速入門,你可以使用正則表達式是這樣的:

import re 
text = "I am 1-321231, human-cyborg relations." 
list_of_codes = re.findall("\d[-]\d*", text) 
+0

這是_searching_而不是_matching_。 –

2

可以使用regular expressions

import re 
text = "1-321231" 
pattern = '\d[-]\d*' 
match = re.match(pattern , text) 
if match: 
    print 'Yes' 
else: 
    print 'No' 
2

首先,你可以試試:

import re 

my_text = #grab text from file 
my_match = re.search(r'\d[-]\d*', my_text) 
print 'Yes' if match else 'No' 

前的字符串確保反斜槓不會被解讀爲轉義字符