简体   繁体   English

python中的正则表达式错误:sre_constants.error:无需重复

[英]Regular expression error in python : sre_constants.error: nothing to repeat

I'm trying to return True only if a letter has a + before and after it 我只在字母前后带有+才尝试返回True

def SimpleSymbols(string): 
if re.search(r"(?<!+)\w(?!+)", string) is None :
    return True
else:
    return False

The unescaped + is a quantifier that repeats the pattern it modifies 1 or more times. 未转义的+是一个量词,可将其修改的模式重复1次或多次。 To match a literal + , you need to escape it. 要匹配文字+ ,您需要对其进行转义。

However, the (?<!\\+) and (?!\\+) will do the opposite: they will fail the match if a char is preceded or followed with + . 但是, (?<!\\+)(?!\\+)将做相反的事情:如果在char之前或之后加上+则它们将使匹配失败。

Also, \\w does not match just letters, it matches letters, digits, underscore and with Unicode support in Python 3.x (or with re.U in Python 2.x) even more chars. 另外, \\w不仅与字母匹配,还与字母,数字,下划线匹配,并且在Python 3.x中具有Unicode支持(在Python 2.x中具有re.U )甚至更多的字符。 You may use [^\\W\\d_] instead. 您可以改用[^\\W\\d_]

Use 采用

def SimpleSymbols(string): 
    return bool(re.search(r"\+[^\W\d_]\+", string))

It will return True if there is a +[Letter]+ inside a string, or False if there is no match. 如果字符串中有+[Letter]+ ,则返回True ,否则返回False

See the Python demo : 参见Python演示

import re

def SimpleSymbols(string): 
    return bool(re.search(r"\+[^\W\d_]\+", string))
print(SimpleSymbols('+d+dd')) # True
print(SimpleSymbols('ddd'))   # False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM