2017-08-05 182 views
3

我有我需要使用RegEx解析以下字符串。C#正則表達式提取字符串括在單引號

abc = 'def' and size = '1 x(3\" x 5\")' and (name='Sam O\'neal') 

這是一個SQL濾波器,我想分成使用以下分離器的令牌,其中:該字符串被解析

(,), >,<,=, whitespace, <=, >=, != 

後,我想輸出是:

abc, 
=, 
def, 
and, 
size, 
=, 
'1 up(3\" x 5\")', 
and, 
(, 
Sam O\'neal, 
), 

我試過下面的代碼:

string pattern = @"(<=|>=|!=|=|>|<|\)|\(|\s+)"; 
var tokens = new List<string>(Regex.Split(filter, pattern)); 
tokens.RemoveAll(x => String.IsNullOrWhiteSpace(x)); 

我不確定如何將單引號中的字符串保留爲一個令牌。我是新來的正規表達,並會感謝任何幫助。

+1

後'(''添加 '[^'] *'|'。 –

+0

Thanks @WiktorStribiżew - 我嘗試了以下模式的建議:'string pattern = @「(<=|> = |!= | = |> | <| \)| \(|'[^'] *'| \ s +) 「;」。雖然字符串文字'1 up(3 \「x 5」)'顯示爲一個標記。但字面上的'Sam O \'neal'顯示爲兩個標記 –

回答

2

您的模式需要另一個備選分支的更新:'[^'\\]*(?:\\.[^'\\]*)*'

它將匹配:

  • ' - 單引號
  • [^'\\]* - 0+字符比'\
  • (?:其他 - 非捕獲組匹配的序列:
    • \\. - 任何轉義序列
    • [^'\\]* - 和0+字符比'其他\
  • )* - 零個或多個
  • ' - 單引號

在C#:

string pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)"; 

regex demo

C# demo

var filter = @"abc = 'def' and size = '1 x(3"" x 5"")' and (name='Sam O\'neal')"; 
var pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)"; 
var tokens = Regex.Split(filter, pattern).Where(x => !string.IsNullOrWhiteSpace(x)); 
foreach (var tok in tokens) 
    Console.WriteLine(tok); 

輸出:

abc 
= 
'def' 
and 
size 
= 
'1 x(3" x 5")' 
and 
(
name 
= 
'Sam O\'neal' 
) 
+0

您的代碼按照提供的方式工作,但如果將字符串更改爲:'string filter ='abc ='def'and size ='1 x(3 \「 x 5 \「)'和(name ='Sam O'neal')」; '。 「Sam O neal」仍然分成單獨的標記,我將從用戶輸入讀取變量。 –

+0

無論如何,我已經使用過你的回答,然後通過用RegEx.Split()之前的特殊字符替換「Sam O \'neal」中的轉義單引號,然後再將其放回來來處理撇號字符串。 –

+0

@AllisonThomas'name ='Sam O'neal''不可能沒有假設匹配。最有可能的是,這是由於設計不佳或者是錯誤造成的。 –