如何在python中处理正则表达式?

时间:2016-06-08 09:55:38

标签: python

我想在我的文本文件“1-321231”中检测到这种格式,我的意思是任何数字,加上' - '加上任何数字, 我写了这个正则表达式:

\d[-]\d*

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

4 个答案:

答案 0 :(得分:3)

“检测”就是我们所说的“匹配”。 以下是如何使用它的工作示例:

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

答案 1 :(得分: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 )

答案 2 :(得分:2)

您可以使用regular expressions

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

答案 3 :(得分:2)

首先,请尝试以下方法:

import re

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

字符串前的r确保反斜杠不会被读取为转义字符