簡體   English   中英

正則表達式提取單引號或雙引號之外的字符串

[英]regex to extract strings outside single or double quotes

我目前正在使用asp.net和C#構建網頁。 我在解析用戶提供的字符串時遇到麻煩。 例如,用戶提供了以下字符串,而我需要提取單引號或雙引號之外的單詞。 有人可以幫我解決這個問題嗎? 提前感謝你的幫助。

"we run" live "experiments" inside and outside 'a lab'

使用正則表達式的預期結果是:

live

inside

and

outside
var parts = Regex.Split(input, @"[""'].+?[""']")
            .SelectMany(x => x.Split())
            .Where(s => !String.IsNullOrWhiteSpace(s))
            .ToList();

要么

var parts = Regex.Split(input, @"[""'].+?[""']")
            .SelectMany(x => x.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries))
            .ToList();

這樣就可以了。 組“ unquote”的所有匹配項都符合您的要求:

(?<unquote>[^"'\s]+)|(?:["][^"]+?["])|(?:['][^']+?['])

C#測試代碼:

 var matches = Regex.Matches( @"""we run"" live ""experiments"" inside and outside 'a lab'", @"(?<unquote>[^""'\s]+)|(?:[""][^""]+?[""])|(?:['][^']+?['])" );
 foreach( Match match in matches )
 {
     if( match.Groups["unquote"].Success )
     {
         Console.WriteLine( match.Groups["unquote"].Value.Trim() );
     }
 }

輸出:

生活

哪里:

  • <unquote>表示放在稱為unquote的組中
  • ^"'\\s表示匹配所有不是雙引號或空格的內容。
  • (?:["][^"]+?["])表示將引號內的所有內容都匹配到下一個引號。請注意+?使其不貪婪,而?:則不捕獲組。引用。

這將適用於空字符串“”和單引號嵌套在雙引號中的字符串。 您是否要忽略撇號? 如果是,那么您將需要稍微擴展正則表達式以允許'前面不能加空格:

(?<unquote>(?>[^"\s](?<!\s[']))+)|(?:["][^"]+?["])|(?:['][^']+?['])

祝您實驗愉快!

暫無
暫無

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

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