Search code examples
qtqregexp

Qt QRegExp replace all URLs in a string with <a> Anchored URLs


Given a QString that can have an unknown number of URL's in it...

How can I use QRegExp to wrap HTML anchor tags around only the URL portions (with the URL itself as clickable label).

e.g.

input: "this is www.cnn.com, that is https://www.mybank.com"

output: "this is <a href="www.cnn.com">www.cnn.com</a>, that is <a href="https://www.mybank.com">https://www.mybank.com</a>

Solution

  • ok. got it.

    QRegExp regExp("((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[\\-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9\\.\\-]+|(?:www\\.|[\\-;:&=\\+\\$,\\w]+@)[A-Za-z0-9\\.\\-]+)((?:\\/[\\+~%\\/\\.\\w\\-]*)?\\??(?:[\\-\\+=&;%@\\.\\w]*)#?(?:[\\.\\!\\/\\\\\\w]*))?)");
    
    QString result = myOriginalString.replace(regExp, "<a href='\\1'>\\1</a>" );
    

    I'll leave the question/answer here for the sake of who may be interested in this.