tags:

views:

25

answers:

1

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://, ftp://, 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>")
+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.)

David Zaslavsky
Thank you, that works great. You are correct, matching potentially invalid URLs is OK for where I need this.
Jake Petroules