tags:

views:

119

answers:

3

Hello, i'm trying to replace a text which contains url's with the text with the tags and i'm trying to use something like this, but i just don't get why this is not working, maybe i'm too tired too see it. Here goes my test:

 [Test]
 public void Check() {
  string expUrl = @"^(https?://)"
  + @"?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
  + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
  + @"|" // allows either IP or domain
  + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
  + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]" // second level domain
  + @"(\.[a-z]{2,6})?)" // first level domain- .com or .museum is optional
  + @"(:[0-9]{1,5})?" // port number- :80
  + @"((/?)|" // a slash isn't required if there is no file name
  + @"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 

  const string url = "http://www.google.com";

  var b = Regex.IsMatch(url, expUrl);
  Assert.IsTrue(b);

  var text = string.Format("this is a link... {0} end of link", url);
  var resul = Regex.Match(text, expUrl);
  Assert.IsTrue(resul.Success);
 }

Why the url variable passes the IsMatch Check, but doesn't pass the Match check? thanks in advance.

+4  A: 

Because you started your regex with ^ and ended with $. Those specify that the match must begin at the start of the string and end at the end. Since your match is in the middle, it was not found.

RandomEngy
Thanks a lot, definitely 5pm is a hard time to not get some bugs
Jhonny D. Cano -Leftware-
+2  A: 

Because your regular expression begins with a "^" character.. indicating that "https" should go FIRST, as well as the $ indicating that the string should end with the last defined group.

if you remove ^ and $, both tests will pass

Ciwee
Thanks a lot, it was very helpful
Jhonny D. Cano -Leftware-
+1  A: 

^(https?://)

You're requiring it to start with http

Update this line from

string expUrl = @"^(https?://)"

to

string expUrl = @"(https?://)"

And update your final line from

+ @"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";

to

+ @"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)";
Chris Ballance