0

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
  • If it seems to work, why do you need another way? What attribute will this other way have that will make it better? – Bryan Oakley Feb 04 '15 at 00:15
  • @BryanOakley I thought there was a simpler way to do it, like setting a parameter `all=True`, but I might be getting crazy – nbro Feb 04 '15 at 00:42
  • @Rinzler, what do you mean by "whole words". Do you just want to find something like `r"\w+"`? – noahbkim Feb 11 '15 at 14:11
  • @noahbkim I mean for example `are` in "How `are` you?" instead of `are` in "What did you `prepare`"? – nbro Feb 12 '15 at 14:31
  • @Rinzler Just develop your regular expression. For as many cases as I can think of off the top of my head, you could just use something like `r"\bare\b"`. – noahbkim Feb 12 '15 at 16:16
  • @noahbkim Yes, that's exactly what I did. At the beginning, I was doing it with the `Text` widget builtin `search` method, but I then decided to create my own searches methods, with Python regular expressions instead of tcl/tk ones (like in my above example). – nbro Feb 12 '15 at 16:37
  • @noahbkim, just a head's up: in Tcl (at least as of version 8.5), the regular expression example that you typed would be `r"\yare\y"` instead of `r"\bare\b"` because in Tcl the `\b` matches a backspace character. – SizzlingVortex Sep 27 '15 at 19:20

1 Answers1

-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.

noahbkim
  • 528
  • 2
  • 13