How can I find text containing url using regular expression?

时间:2017-11-08 22:10:00

标签: c# regex

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?

1 个答案:

答案 0 :(得分:1)

删除[\w+?\.\w+]周围的方括号,你应该很好。方括号内的字符按任何顺序匹配。

在此处试试:https://regex101.com/r/X2nUNA/1