PyQt5: how to do replacement using QRegularExpression

185 views Asked by At

I want to reserve all English characters and replace others. When using 're' module, it looks like that:

name = 'srw  959we'
result = sub('/W', '', name)

Then I get name = 'srwwe'. Now I want to use the class QRegularExpression to realize that, but the official document is so abbreviated that I found nothing useful. It will be appreciated if someone can give a brief and clear example for PyQt.

1

There are 1 answers

1
ekhumoro On BEST ANSWER

This cannot be done, because it requires the QString class, which is not included in PyQt (and the same goes for PySide). The equivalent to re.sub in Qt is QString.replace, and there is just no way to access it from PyQt. (The QRegularExpression.swap method does something entirely different, so is no help either).

QRegularExpression is only really useful in PyQt where you need to access a Qt API that requires passing an object of that type. For general string manipulation, just use Python's re module (or regex if you need additional functionality).