【问题标题】:Regex can't escape question mark? [duplicate]正则表达式无法逃脱问号? [复制]
【发布时间】:2014-09-25 14:01:12
【问题描述】:

虽然我转义了问号字符,但我无法匹配它。
我尝试使用多个反斜杠转义并使用re.escape()

我错过了什么?

代码:

import re

text = 'test?'
result = ''

result = re.match(r'\?',text)

print ("input: "+text)
print ("found: "+str(result))

输出:

input: test?
found: None

【问题讨论】:

    标签: python regex python-3.x escaping


    【解决方案1】:

    re.match 只匹配字符串开头的模式;如文档中所述:

    如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的匹配对象。

    所以,要么:

    >>> re.match(r'.*\?', text).group(0)
    'test?
    

    re.search

    >>> re.search(r'\?', text).group(0)
    '?'
    

    【讨论】:

    • 谢谢,我不知道字符串的“开头”是什么意思(当字符串不包含空格时),因为正则表达式通常匹配任何位置。
    • @radry 这不是关于正则表达式,而是关于使用该正则表达式的函数。
    猜你喜欢
    • 2012-07-16
    • 2012-01-30
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多