[英]How find whole words in tkinter text widget and not strings part of a word
我现在的代码 -
def find():
#remove tag 'found' from index 1 to END
text.tag_remove('found', '1.0', END)
#returns to widget currently in focus
s = edit.get()
if s:
idx = '1.0'
while 1:
#searches for desired string from index 1
idx = text.search(s, idx, nocase=1,
stopindex=END)
if not idx: break
#last index sum of current index and
#length of text
lastidx = '%s+%dc' % (idx, len(s))
#overwrite 'Found' at idx
text.tag_add('found', idx, lastidx)
idx = lastidx
#mark located string as red
text.tag_config('found', foreground='red')
edit.focus_set()
问题是——如果我需要找到"hell"
,它也会在"hello"
中突出显示地狱,但我只需要检测整个单词。 一个简单的解决方案是搜索" hell "
,但它不适用于像"hell is my hell"
这样的字符串
您可以搜索正则表达式,并使用单词开头和单词结尾约束来锚定搜索字符串。 要使用正则表达式搜索,请在调用search
时将regexp
参数设置为True
并用单词开始约束 ( \m
) 和单词结束约束 ( \M
) 包围目标字符串。
这是需要更改的几行:
pattern = f"\\m{s}\\M"
while 1:
idx = text.search(pattern, idx, nocase=1,
stopindex=END, regexp=True)
重要的是要知道文本小部件使用底层 Tcl 解释器的正则表达式引擎,这与 python 使用的略有不同。 完整的描述可以在re_syntax手册页中找到。
此外,您自己对“单词”的定义可能与 tcl 对“单词”的定义不同。 如果是这种情况,您可以使用任何您想要的模式来代替内置的单词约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.