How do I use QString::replace
to detect URLs in a string and replace them with an HTML link, like so...
[...].replace(QRegExp("???"), "<a href=\"\\1\">\\1</a>")
What should the argument to QRegExp
be? The end of a URL should be denoted by the occurrence of a whitespace character (such as space, \r or \n) or the end of the string.
The regex should be fairly simple: http://, https://, f开发者_如何学Pythontp://, etc, followed by one or more non-whitespace characters, should be converted to a link.
EDIT: This is the solution I used...
[...].replace(QRegExp("((?:https?|ftp)://\\S+)"), "<a href=\"\\1\">\\1</a>")
I think (?:https?|ftp)://\\S+
will do it for you.
Don't forget that this will potentially match some invalid URLs, but that's probably OK for your purposes. (A regex that matches only syntactically valid URLs would be quite complicated to construct and not worth the effort.)
精彩评论