簡體   English   中英

當不在一組引號內時匹配正則表達式模式(文本跨越多行)

[英]Match regex pattern when not inside a set of quotes (text spans multiple lines)

這是我之前的問題.NET 正則表達式引擎不返回匹配項但我期待 8的延續。

我的查詢完美地處理了所有事情,並且我的捕獲組工作得很好,但是我發現了一個我不知道如何處理的邊緣情況。

這是我遇到問題的測試用例

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,但我在處理這兩個問題時遇到了麻煩。

如果我有辦法檢查捕獲組中是否有偶數個' s` 我可以檢查然后看看我們是在真正的行尾還是在有一行結束的文本塊中恰好與模式匹配。 但我不知道如何修改其他示例來處理多行文本字符串。

我可以用一個正則表達式查詢來完成我想做的事情,還是我被迫進行后處理(使用注釋的案例)並且這是兩次通過?


這是在 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();

像這樣的表達式將匹配這樣的引號:

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

如果你想在foo不在這樣的引號內時匹配它,你可以使用類似的東西:

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

每行一個匹配項,未加引號的文本和數字作為捕獲組

像這樣:

(?xm)^
\(

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

\)
[;,] 
\r?$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM