Search for whole words in the Text widget with the search method

霸气de小男生 提交于 2020-01-03 00:54:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!