开发者

Help with a .net regex

  1. var a = @"Blah <a href=""{0}"">blah</a>"
  2. if ( b == "")
  3. if (c =="")
  4. var d = ""
  5. var e=""

Looking for a .Net regex that will match lines 2 - 5, but not 1. The input is each line. Bascially I am tying to distinguish between A. using "" in a @ prefixed string literal and B. using "" where str开发者_开发百科ing.Empty would be better.

=\s*"" is my start, but it matches all 5 lines. How can I modify it to not match 1, but match the others? Modify it in someway to incorporate ^@?


With reservation, this meets the five cases of the question:

^[^=]*==?\s*""

Breakdown:

^      start of line
[^=]*  any number of characters that are not equals
=      a literal equals
=?     an optional second equals
\s*    any amount of whitespace ('@' here prevents a match)
""     an empty string

However, using regular expressions in this kind of situation is dangerous as it is not sensitve to the language grammar. It would be all to easy to come up with some code where this regular expression matches but is not what you intended or where this regular expresison does not match when you expect it to. A truly comprehensive regular expression would be virtually impossible to write and maintain.


A simple approach would be this:

={1,2}\s*""

This obviously will match your first example, too. To not match your first example and other cases where that pattern is not used as a statement, you would more or less need to build a syntax parser for C# code.
I don't think, that Regex is the best solution for this task...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜