问题
I am trying to find a way to match whole words using the Tkinter Text
search method, but I have not found a consistent way of doing it. I have tried to set regexp
to True
and then use word boundaries of the Tcl
regular expressions, with \y
wrapping the word:
pos = text_widget.search('\\y' + some_word +'\\y', start, regexp=True)
It seems to work, but I think there might exist another way of doing it.
回答1:
Here is a snippet of code that will allow you to search for any regular expression in the text widget by using the tcl character indexing 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 are dependent on the tkinter.Text.search function, I believe the idlelib EditorWindow
class uses it to do its syntax highlighting.
来源:https://stackoverflow.com/questions/28310464/search-for-whole-words-in-the-text-widget-with-the-search-method