簡體   English   中英

無法使用正則表達式在雙引號之間提取字符串

[英]Unable to extract string between double quotes using regex

我試圖使用正則表達式提取用雙引號括起來的子串:

"\w[\w\s\t]*"

在字符串上:

“@test”跳過“2 3”跳過“TEST”跳過“te st”跳過“@#”

已成功提取粗體子串。 但是沒有提取具有特殊字符的那些。 請幫我解決這個問題。 我不是那么專業地制作正則表達式。

這個正則表達式應該工作

"(.+?)"

Regex101演示

它使用了組捕獲的概念

正如埃克斯在評論中所說,試着用

“[^”] *”

這應該匹配一個引號,然后匹配任何數量的非引號字符,然后是另一個引號。 其他答案將不匹配0長度,具體取決於您是否想要它。

string input = @"""@test"" skip ""2 3"" skip ""TEST"" skip ""te st"" skip ""@#""";
var values = Regex.Matches(input, @"\""(.+?)\""")
                  .Cast<Match>()
                  .Select(m => m.Groups[1].Value)
                  .ToList();

您還可以匹配包含轉義雙引號的子字符串:

正則表達式: ".+?(?<!\\\\)"

碼:

var txt1 = "\"This is \\\"some text\\\" to capture\" \"no other text\"";
var regex1 = new Regex(@""".+?(?<!\\)""", RegexOptions.IgnoreCase  | RegexOptions.CultureInvariant);
var c1 = regex1.Matches(txt1).Cast<Match>().Select(d => d.Value.Trim()).ToList();

輸出:

"This is \"some text\" to capture"
"no other text"

暫無
暫無

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

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