奇怪的行为重新匹配Python 3中的函数

2024-03-29 15:56:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我希望程序打印“Match”,因为"\D+\d"匹配字符串的"x4"部分。但它不打印任何东西。有什么问题?你知道吗

import re
pattern = r"\D+\d"
if re.match(pattern, "1x4"):
    print("Match");

谢谢


Tags: 字符串代码import程序reifmatchpattern
1条回答
网友
1楼 · 发布于 2024-03-29 15:56:43

您认为re.match可以匹配字符串中的任何位置的假设是错误的。你知道吗

https://docs.python.org/2/library/re.html#re.RegexObject.match

If zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

改用re.search()。你知道吗

相关问题 更多 >