Vrisk
Vrisk

Reputation: 221

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

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

Upvotes: 0

Views: 53

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627344

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('ddd'))   # False

Upvotes: 1

Related Questions