Exclude words that contain my regular expression but are not my regular expression Exclude words that contain my regular expression but are not my regular expression tkinter tkinter

Exclude words that contain my regular expression but are not my regular expression


You can use anchors:

"^(?:if|def)$"

^ asserts position at the start of the string, and $ asserts position at the end of the string, asserting that nothing more can be matched unless the string is entirely if or def.

>>> import refor foo in ["if", "elif", "define", "def", "in"]:    bar = re.search("^(?:if|def)$", foo)    print(foo, ' ', bar);... if   <_sre.SRE_Match object at 0x934daa0>elif   Nonedefine   Nonedef   <_sre.SRE_Match object at 0x934daa0>in   None


You could use word boundaries:

"\b(if|def)\b"


The answers given are ok for Python's regular expression, but I have found in the meantime that the search method of a tkinter Text widget uses actually the Tcl's regular expressions style.

In this case, instead of wrapping the word or the regular expression with \b or \\b (if we are not using a raw string), we can simply use the corresponding Tcl word boundaries character, that is \y or \\y, which did the job in my case.

Watch my other question for more information.