Regular expression error in python : sre_constants.error: nothing to repeat

前端 未结 1 860
情话喂你
情话喂你 2021-01-27 10:03

I\'m trying to return True only if a letter has a + before and after it

def SimpleSymbols(string): 
if re.search(r\"(?

        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 10:51

    The unescaped + is a quantifier that repeats the pattern it modifies 1 or more times. 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 +.

    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. You may use [^\W\d_] instead.

    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.

    See the Python demo:

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

    0 讨论(0)
提交回复
热议问题