brinch
brinch

Reputation: 2614

How can I find text containing url using regular expression?

I am trying to create a method that will return true, if the passed in text parameter contains a url. Here is what I have so far:

private bool TextContainsUrl(string text)
{
  Regex rgx = new Regex(@"((http|ftp|https|www)://)?([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?");
  bool match = rgx.IsMatch(text);

  return match;
}

I might call it like:

TextContainsUrl("here is a text with url http://something.net bla bla.");

or

TextContainsUrl("here is a text with no url bla bla.");

Problem is, that both calls above return true.

What am I doing wrong here?

Upvotes: 0

Views: 40

Answers (1)

omijn
omijn

Reputation: 656

Remove the square brackets around [\w+?\.\w+] and you should be good. Characters within square brackets are matched in any order.

Try it here: https://regex101.com/r/X2nUNA/1

Upvotes: 1

Related Questions