简体   繁体   English

为什么此C#正则表达式不起作用?

[英]Why isn't this C# Regex working?

I have the following string (from a large HTML string): 我有以下字符串(来自大型HTML字符串):

href="/cgi-bin/pin.cgi?pin=94841&sid=9548.1386389012.v1"><

And here is my code: 这是我的代码:

var sids = Regex.Matches( htmlCode, "sid=(.)\">" );

I'm not pulling back any results. 我不会撤回任何结果。 Is my Regex correct? 我的正则表达式正确吗?

This is what it should be: 这是应该的:

var str = @"href=""/cgi-bin/pin.cgi?pin=94841&sid=9548.1386389012.v1"">";
var sid = Regex.Match(str, @"sid=([^""]*)");
Console.WriteLine (sid.Groups[1].Value);

What you originally posted was wrong because "." 您最初发布的内容是错误的,因为“。” acts as a wildcard, and the way you presented it meant that it would only capture 1 character, the problem with wildcards is that they're difficult to stop till you reach the end of a line, so never use them unless you have to. 充当通配符,并且您呈现它的方式意味着它只能捕获1个字符,通配符的问题在于,直到到达行尾之前,它们很难停止,因此除非必须使用,否则请不要使用它们。

. match only single character. 仅匹配单个字符。 To match multiple character you should use * or + modifier: (.+) ; 要匹配多个字符,应使用*+修饰符: (.+) ; or more preferably non-greedy version: (.+?) 或更可取的是非贪婪版本: (.+?)

Use @"verbatim string literal" if possible for regular expression. 如果可能,请使用@"verbatim string literal"进行正则表达式。

var sids = Regex.Matches(htmlCode, @"sid=(.+?)""");

See demo run . 请参阅演示运行

I think you are pretty close. 我觉得你很亲密。 Consider the following minor change to your regex... 考虑对您的正则表达式进行以下较小的更改...

sid=.*?\">

Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM