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

扶醉桌前 提交于 2019-12-02 00:58:27
Bryan Oakley

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.

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