使用搜索方法在“文本”小部件中搜索整个单词

时间:2015-02-03 23:02:48

标签: regex search python-3.x text tkinter

我正在尝试使用Tkinter Text 搜索方法找到匹配整个单词的方法,但我还没有找到一致的方法。我尝试将regexp设置为True,然后使用Tcl正则表达式的单词边界,\y包含该单词:

pos = text_widget.search('\\y' + some_word +'\\y', start, regexp=True)

它似乎有用,但我认为可能存在另一种方法。

1 个答案:

答案 0 :(得分:0)

以下是一段代码,可让您使用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+")

但是,如果你依赖于tkinter.Text.search函数,我相信idlelib EditorWindow类使用它来进行语法高亮。