正则表达式以匹配URL

时间:2018-10-03 17:49:03

标签: c# regex

我是新来的正则表达式。我需要匹配以下几行:

  1. / api / v1 / user / [^ /?#] + / users
  2. / api / v1 / user / some-id / users

我的代码是

url1="/api/v1/user/[^/?#]+/users";

url2="/api/v1/user/some-id/users";

var ll = System.Text.RegularExpressions.Regex.IsMatch(url1, @"^("+Regex.Escape(url2)+"):");

1 个答案:

答案 0 :(得分:1)

根据评论,要同时匹配/api/v1/user/some-id/users/api/v1/role/134/users,请使用alternation

^/api/v1/(?:user|role)/[^/?#]+/users

String regex="^/api/v1/(?:user|role)/[^/?#]+/users";
String url2="/api/v1/user/some-id/users";
Console.WriteLine(System.Text.RegularExpressions.Regex.IsMatch(url2, regex));

C# demo