首页 > 解决方案 > 为什么 re.search 打印匹配发现即使字符串也不完全相同

问题描述

我的string_first匹配patternpattern_second(见下面的代码)。但是,我希望它只与pattern_second. 有人可以帮助我实现这一目标吗?

import re

string_first = "this-is-first-time"
pattern = "this-is-first"
pattern_second = "this-is-first.*"

if re.search(pattern, string_first):
    print("string match for pattern first")
else:
    print("string not match")

if re.search(pattern_second, string_first):
    print("string match for pattern second")
else:
    print("string not match")

标签: pythonregex

解决方案


在您的模式中指定您的行尾如下:

pattern = "this-is-first$"

'$' 表示行尾。


推荐阅读