正则表达式以测试存在并同时匹配字符串

时间:2011-03-18 23:08:05

标签: python regex

我想确定一个字符串S是否有一个子串MYSUBSTRING,前面是我需要确定的两个连续数字。

例如:

'aaa79bbbMYSUBSTRINGccc​​' ==>我想要7,9和True(或7,9和MYSUBSTRING)

'aaa79bbbccc' ==>我想要7,9和False(或7,9和无)

我可以使用SINGLE正则表达式吗?如果是这样,哪一个?

3 个答案:

答案 0 :(得分:4)

以下正则表达式应该这样做:

(\d)(\d)(?:.*?(MYSUBSTRING))?

>>> re.search(r'(\d)(\d)(?:.*?(MYSUBSTRING))?', 'aaa79bbbMYSUBSTRINGccc').groups()
('7', '9', 'MYSUBSTRING')
>>> re.search(r'(\d)(\d)(?:.*?(MYSUBSTRING))?', 'aaa79bbbccc').groups()
('7', '9', None)

答案 1 :(得分:0)

当然,您可以使用(\d)(\d).*?(MYSUBSTRING)?。在Python中,您可以在re.search函数中使用它,如下所示:

s = ... # your string
m = re.search(r'(\d)(\d).*?(MYSUBSTRING)?', s)
m.group(1) # first digit
m.group(2) # second digit
m.group(3) # the substring, or None if it didn't match

答案 2 :(得分:0)

一个有趣的问题。这种怪异:

(\d)(\d)(.(?!(MYSUBSTRING)))*.?(MYSUBSTRING)?

似乎适合我。

细分:

(\d)(\d)              # capture 2 digits
(.(?!(MYSUBSTRING)))* # any characters not preceded by MYSUBSTRING
.?                    # the character immediately before MYSUBSTRINg
(MYSUBSTRING)?        # MYSUBSTRING, if it exists