【问题标题】:Python string must match beginning of regex but not end [duplicate]Python字符串必须匹配正则表达式的开头但不匹配结尾[重复]
【发布时间】:2017-02-14 14:59:38
【问题描述】:

我觉得这种行为有点奇怪:

pattern = re.compile(r"test")
print pattern.match("testsda") is not None
True
print pattern.match("astest") is not None
False

所以,当字符串与结尾的模式不匹配时,一切都很好。但是当字符串在其开头不匹配模式时,字符串不再匹配模式。

相比之下,grep 在这两种情况下都成功:

echo "testsda" | grep  test
testsda
echo "adtest" | grep  test
adtest

你知道为什么会这样吗?

【问题讨论】:

标签: python regex grep


【解决方案1】:

re.match 旨在仅匹配字符串的开头。作为docs 状态:

Python 提供了两种不同的基于常规的原始操作 表达式:re.match() 仅在开头检查匹配 字符串,而 re.search() 检查 字符串(这是 Perl 默认所做的)。

如果你使用re.search,应该没问题:

import re

pattern = re.compile(r"test")
print pattern.search("testsda") is not None
print pattern.search("astest") is not None

打印

True
True

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 2022-08-03
    • 2016-12-07
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多