How to use a regular expression in Tkinter text search method? How to use a regular expression in Tkinter text search method? tkinter tkinter

How to use a regular expression in Tkinter text search method?


You have two problems. First, you are putting positional arguments in the wrong order. The first positional argument is expected to be the pattern, and the second positional argument is treated as the start index. Since your second argument is an instance of SRE_Pattern, you get the bad text index error.

You need to change the order of your arguments so that your first argument is the pattern. The next two arguments should be the start and end indexes.

Second, when you set regexp to True, you must still pass the pattern in as a string. The text widget will interpret that string as a regular expression. You cannot pass in a compiled regular expression.

Here's an example that should work:

index = text.search(r'\[A.*\]', "1.0", END, count=countVar, regexp=True)

FWIW, this answer to the question Tkinter text highlighting in python gives an example of subclassing the Text class to add a method named highlight_pattern.