0

Please consider this string:

http://tempuri.org/IService1/GetData\

I want to get GetData using regular expression. I test it with this code:

Regex regex = new Regex("\\/\\w*\\");

But I get this error:

System.ArgumentException: 'parsing "/\w*\" - Illegal \ at end of pattern.'

and then I test this code:

Regex regex = new Regex(@"\/\w*\\");

but it doesn't work and doesn't recognize any match.

Hot I can recognize GetData in above string using regular expression?

Thanks

Arian
  • 12,793
  • 66
  • 176
  • 300

1 Answers1

1
var input = @"http://tempuri.org/IService1/GetData\";
Regex regex = new Regex(@"/(\w*)\\");
var match = regex.Match(input);
if (match.Success)
{
    //  data = "GetData"
    var data = match.Groups[1].Value;
}

Regex("\\/\\w*\\") after backslashes escaping results to regular expression \/\w*\ . This expression is incorrect because of tailing backslash. That causes Illegal \ at end of pattern error.

With so many backslashes that should be escaped in RE, there is a big chance to make a mistake. This is a reason why it's better to use verbatim strings when you build regular expression. The same regular expression with usual C# string should be built as new Regex("/(\\w*)\\\\$"). Those four slashes at the end are just killing me.

CodeFuller
  • 30,317
  • 3
  • 63
  • 79
  • Thanks but your pattern does not recognize `GetData` in `var input3 = "\"http://tempuri.org/IService1/GetData\"";` – Arian Mar 18 '18 at 10:48
  • If backslash could be not the last character of the input string, then you should just remove `$` from my original regular expression. I've edited the answer. – CodeFuller Mar 18 '18 at 12:03