Find whole words in a text widget using the search method
I'm trying to find a way to match whole words using Tkinter's search method Text
, but I haven't found a consistent way to do it. I tried setting regexp
to True
and then using regex word boundaries Tcl
, while doing the \y
word wrapping:
pos = text_widget.search('\\y' + some_word +'\\y', start, regexp=True)
This seems to work, but I think there might be another way to do it.
source to share
Here is a code snippet that will allow you to search for any regex in a text widget using the tcl-symbolic syntax :
import tkinter
import re
root = tkinter.Tk()
text = tkinter.Text(root)
text.pack()
def findall(pattern, start="1.0", end="end"):
start = text.index(start)
end = text.index(end)
string = text.get(start, end)
indices = []
if string:
last_match_end = "1.0"
matches = re.finditer(pattern, string)
for match in matches:
match_start = text.index("%s+%dc" % (start, match.start()))
match_end = text.index("%s+%dc" % (start, match.end()))
indices.append((match_start, match_end))
print(indices)
root.after(200, findall, pattern)
root.after(200, findall, r"\w+")
However, if you depend on the tkinter.Text.search function, I believe the class idlelib EditorWindow
uses it for syntax highlighting.
source to share