如何在Tkinter文本搜索方法中使用正则表达式? [英] How to use a regular expression in Tkinter text search method?

查看:134
本文介绍了如何在Tkinter文本搜索方法中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个在方括号内突出显示的区域.这些方括号可以包含任何文本:[A hello world] [B this is a tree] [A tkinter documentation is bad]

I want to find an area for highlighting within square brackets. These square brackets may contain any text: [A hello world] [B this is a tree] [A tkinter documentation is bad]

我想突出显示方括号中带有"A"字符的单词,如下所示:

I want to highlight the words in the brackets that have "A" character with them, like this:

要获取起始索引和匹配的字符数,我尝试了以下方法:

To get the starting index and the number of the matched characters I tried this:

countVar = StringVar()
reg_area = re.compile(r'\[A.*\]')
index = text.search('1.0', reg_area, stopindex=END, count=countVar, regexp = True)

这不起作用,我收到了.

This does not work and I receive.

TclError: bad text index "<_sre.SRE_Pattern object at 0x3856d78>"

如何找到所有发生的事件并正确突出显示它们?

How do I find all occurences and correctly highlight them?

推荐答案

您有两个问题.首先,您将位置参数置于错误的顺序.预期第一个位置参数是模式,第二个位置参数被视为起始索引.由于您的第二个参数是SRE_Pattern的实例,因此您会收到错误的文本索引错误.

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.

第二,当您将regexp设置为True时,仍必须将模式作为字符串传递.文本小部件会将该字符串解释为正则表达式.您不能传入已编译的正则表达式.

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,对于问题此答案 /7432>使用python高亮显示Tkinter文本给出了一个继承Text类以添加名为highlight_pattern的方法的示例.

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.

这篇关于如何在Tkinter文本搜索方法中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆