Python 在 python PyQT5 中包含外来字符的正则表达式

Python regular expressions with Foreign characters in python PyQT5

这个问题可能非常简单,但我发现它有点令人困惑,这就是我需要帮助的原因。

关于 我发布的相关问题已解决,我发现了一个我刚刚注意到的新问题。


源代码:

from PyQt5 import QtCore,QtWidgets

app=QtWidgets.QApplication([])

def scroll():
    #QtCore.QRegularExpression(r'\b'+'cat'+'\b')
    item = listWidget.findItems(r'\bcat\b', QtCore.Qt.MatchRegularExpression)
    for d in item:
        print(d.text())

window = QtWidgets.QDialog()
window.setLayout(QtWidgets.QVBoxLayout())
listWidget = QtWidgets.QListWidget()
window.layout().addWidget(listWidget)


cats = ["love my cat","catirization","cat in the clouds","catść"]

for i,cat in enumerate(cats):
    QtWidgets.QListWidgetItem(f"{i}  {cat}", listWidget)

btn = QtWidgets.QPushButton('Scroll')
btn.clicked.connect(scroll)
window.layout().addWidget(btn)
window.show()
app.exec_()

输出GUI:


现在你可以看到,当我按下 "Scroll" 按钮时,我只是试图打印出基于正则表达式 r"\bcat\b" 的文本数据并且它起作用了很好!

输出:

0  love my cat
2  cat in the clouds
3  catść

但是...正如您在 #3 中看到的那样,它不应该被打印出来,因为它显然与提到的 [=16] 的正则表达式不匹配=].然而它确实如此,我认为它与那个特殊的外来字符 ść 有关,它使它匹配并打印出来(它不应该是正确的?)。

我期待这样的输出:

0  love my cat
2  cat in the clouds

我尝试过的研究

我找到了 this question,它说了一些关于这个 \p{L} 的内容,并根据答案表示:

If all you want to match is letters (including "international" letters) you can use \p{L}.

老实说,我不太确定如何将它应用到 PyQT5 中,我仍然进行了一些尝试,并且尝试将正则表达式更改为这样 r'\b'+r'\p{cat}'+r'\b'。但是我得到了这个错误。

QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object
QString::contains: invalid QRegularExpression object

显然该错误表明它不是有效的正则表达式。有人可以教我如何解决这个问题吗?谢谢!

一般来说,当您需要让您的 shorthand 字符 类 和单词边界识别 Unicode 时,您需要将 QRegularExpression.UseUnicodePropertiesOption 选项传递给正则表达式编译器。见 QRegularExpression.UseUnicodePropertiesOption reference:

The meaning of the \w, \d, etc., character classes, as well as the meaning of their counterparts (\W, \D, etc.), is changed from matching ASCII characters only to matching any character with the corresponding Unicode property. For instance, \d is changed to match any character with the Unicode Nd (decimal digit) property; \w to match any character with either the Unicode L (letter) or N (digit) property, plus underscore, and so on. This option corresponds to the /u modifier in Perl regular expressions.

在 Python 中,您可以将其声明为

rx = QtCore.QRegularExpression(r'\bcat\b', QtCore.QRegularExpression.UseUnicodePropertiesOption)

但是,由于 QListWidget.findItems 不支持 QRegularExpression 作为参数并且只允许将正则表达式作为字符串对象,因此您只能使用 (*UCP) PCRE 动词替代:

r'(*UCP)\bcat\b'

确保在正则表达式开头定义它。