不在一组引号内时匹配正则表达式模式(文本跨越多行)

时间:2012-04-05 16:32:54

标签: c# .net regex

这是我之前的问题.NET regex engine returns no matches but I am expecting 8的延续。

我的查询完美地处理了一切,我的捕获组工作得非常好,但是我发现了一个我不知道如何处理的边缘情况。

Here is a test case我遇到了麻烦。

INSERT INTO [Example] ( [CaseNumber] , [TestText] )
VALUES
(1 , 'Single Line Case'),
(2 , 'Multi
Line Case');
(3 , 'Two Lines with odd end '');
Case');
(4 , ''),
(5 , 'Case 3 is the Empty Text Case');

以下是我使用的模式,我使用的是RegexOptions标记SinglelineMultilineExplicitCaptureIgnorePatternWhitespace

^\(
((('(?<s>.*?)'(?!')) |
 (?<n>-?[\d\.]+)
 )(\s,\s)?
)+
#(?<!'')   #Commented Case 3 works, un-commented case 2 works
\)[;,]\r?$

我可以处理案例3或案例4但我在处理这两个问题时都遇到了问题。

如果我有办法检查捕获组中是否有偶数',我可以检查一下,看看我们是在一个真正的行尾还是在文本块中有一条线结束,恰好匹配模式。但我无法弄清楚如何修改other examples以处理多个带衬里的文本字符串。

我可以用单个正则表达式查询完成所需的操作,还是我被迫进行后期处理(使用注释的情况)并执行此操作是两次通过?


以下是在LINQPad中运行它的代码

string text = 
@"INSERT INTO [Example] ( [CaseNumber] , [TestText] )
VALUES
(1 , 'Single Line Case'),
(2 , 'Multi
Line Case');
(3 , 'Two Lines with odd end '');
Case');
(4 , ''),
(5 , 'Case 3 is the Empty Text Case');
";

const string recordRegex =
@"^\(
((('(?<s>.*?)'(?!')) |
 (?<n>-?[\d\.]+)
 )(\s,\s)?
)+
#(?<!'')   #Commented Case 3 works, un-commented case 2 works
\)[;,]\r?$";

var records = Regex.Matches(text, recordRegex, RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
records.Dump();

1 个答案:

答案 0 :(得分:1)

这样的表达式会匹配这样的引号:

(?:'[^']*')+

如果您想在{em> 这些引号内匹配foo,可以使用以下内容:

foo(?=[^']*(?:'[^']*'[^']*)+\z)

  

每行一个匹配,未加引号的文本和数字作为捕获组

这样的事情:

(?xm)^
\(

(?:
    (?:
        (?<quote> (?:'[^']*')+ )
    |   (?<num>   -?\d+(?:\.\d+)? )
    |   (?<x>     X'[0-9a-f]*' )
    )
    (?:\s*,\s*)?
)+

\)
[;,] 
\r?$