Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...