2

我很想知道为什么模式在 C# 代码中不匹配,而 sme 在http://gskinner.com上成功执行。模式是:

^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$

我要匹配

我在 C# 中尝试过——

YoutubeVideoRegex = new Regex(@"^http:\/\/(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$", RegexOptions.IgnoreCase);

youtubeMatch = YoutubeVideoRegex.Match(url);
if (youtubeMatch.Success)
{
id = youtubeMatch.Groups[1].Value; // I want this                
}

但它不匹配。请问有什么帮助吗?

4

2 回答 2

3

You are trying to access Groups[1], but it doesn't look like your regular expression has captured any groups. Can't you just use youtubeMatch.ToString or Groups[0] to get what you're after (the whole match?) instead of trying to access sub-groups that you haven't defined?

EDIT

Your expression seems to work better when I remove the ?: from the last set of parentheses. My understanding is that if your parenthesized expression starts with ?: you are explicitly indicating that you don't want the expression to be captured into a group, and if it starts with ?= you are defining a zero-width assertion, which, because it is zero-width, obviously doesn't capture anything. You need some parentheses in your expression that actually do capture something if you want Groups to be populated.

EDIT

Based on comments so far and some guessing at what you're trying to do, here is an updated regular expression and some updated code to demonstrate it. It works with the 2 URLs you mentioned in your comment where one would not work:

var re = new System.Text.RegularExpressions.Regex(
   @"^http:\/\/(?:www\.)?youtube.com\/watch\?[^?]*v=(\w+)\b[^\s?]*$",
   System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var match = re.Match(textBox1.Text);
if (match.Success)
{
   textBox2.Text = match.Value;

   if (match.Groups.Count > 1)
      textBox3.Text = match.Groups[1].Value;
   else
      textBox3.Text = "Group missing";
}
else
{
   textBox2.Text = "(No match)";
   textBox3.Text = string.Empty;
}

textBox2 is populated with the whole matching URL and textBox3 is populated with just the "v" query parameter.

于 2013-10-17T16:28:18.233 回答
2

我刚刚运行了你的代码,它与你的两个例子匹配 http: ->

http://www.youtube.com/watch?v=zcKEjSYJVLs&feature=topvideos_sports http://www.youtube.com/watch?v=KsH63qJlIMM

但不是在这个->

www.youtube.com/watch?v=KsH63qJlIMM

因为它显然没有http:您的正则表达式所要求的。你希望它是可选的吗?

如果是这样,那就去做吧:

^(http:\/\/)?(?:www\.)?youtube.com\/watch\?(?=[^?]*v=\w+)(?:[^\s?]+)?$

它很好地抓住了它

于 2013-10-17T16:25:58.440 回答