-1

I am trying to search in a sentence string a link address and make it clickable. does anyone knows what is the regex expression to find http/https/www/ftp links? I will also be glad for some code example

  • Does this answer your question? [Regex to find URLs in a string](https://stackoverflow.com/questions/12587892/regex-to-find-urls-in-a-string) – Andy Lester May 31 '22 at 15:07
  • 1
    Does this answer your question? [Detect URLs in text with JavaScript](https://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript) – Artyom Vancyan May 31 '22 at 15:21

1 Answers1

0

Please use this regex

\b(?:https?:\/\/|www\.|ftp:\/\/)[^\s]*

Explanation

  • \b Word boundary
  • (?: Non-capturing group
    • https?:\/\/|www\.|ftp:\/\/ Match either http:// or https:// or www. or ftp://
  • ) Close non-capturing group
  • \S* Anything except the space

Also, see the demo

Python Example

import re

text = """http://google.com is same as google.com.
https://stackoverflow.com is my favorite community.
Visit www.stackoverflow.com every day.
ftp://google.com/photos/upload"""

re.findall(r"\b(?:https?:\/\/|www\.|ftp:\/\/)\S*", text)  # ['http://google.com', 'https://stackoverflow.com', 'www.stackoverflow.com', 'ftp://google.com/photos/upload']

JavaScript Example

let text = `http://google.com is same as google.com.
https://stackoverflow.com is my favorite community.
Visit www.stackoverflow.com every day.
ftp://google.com/photos/upload`

text.match(/\b(?:https?:\/\/|www\.|ftp:\/\/)\S*/g)  // ['http://google.com', 'https://stackoverflow.com', 'www.stackoverflow.com', 'ftp://google.com/photos/upload']
Artyom Vancyan
  • 2,348
  • 3
  • 10
  • 28