pythonpyqtpyqt4qregexp

QregExp class PyQt4


I am trying to achieve the following, however with the QRegExp class in PyQt4.

I am struggling to find good examples on how to use this class in python.

def html_trap(text):
    h ={"&":"&amp;",'"':"&quot;","'":"&apos;",">":"&gt;","<":"&lt;"}
    t=""
    for key,value in h.items():
        m=re.search(value,text)
        if m is not None:
            t=text.replace(value,key)
    return t

print(html_trap("Grocery &quot; Gourmet Food"))

Thanks


Solution

  • Instead of search you must use search() you must use indexIn(), this returns the position of the found element or -1 if you can not find it

    from PyQt4 import QtCore
    
    
    def html_trap(text):
        h ={"&": "&amp;",'"':"&quot;","'":"&apos;",">":"&gt;","<":"&lt;"}
        t=""
        for key, value in h.items():
            regex = QtCore.QRegExp(value)
            if regex.indexIn(text) != -1:
                t = text.replace(value, key)
        return t
    
    print(html_trap("Grocery &quot; Gourmet Food"))
    

    Output:

    Grocery " Gourmet Food