[英]Regex to get string between \“ and \”
由於我是正則表達式的新手,所以我想在這里獲得幫助。
var test =“ and([[family]:\\”樹木\\“或[family]:\\”顏色\\“)”
我想提取家庭名單:
樹木
顏色
我使用了以下模式。
Regex.Matches(test, @"[family]:\*\");
它對我不起作用,任何建議都將有所幫助。
您可以使用
Regex.Matches(filters.queryString, @"\[family]:\s*""([^""]*)""")
.Cast<Match>()
.Select(m => m.Groups[1].Value.Trim())
.ToList();
您需要的值在組1中,並且使用.Trim()
, .Trim()
前導/后綴空格從這些子字符串中刪除。
圖案細節
\\[family]:
- [family]
子字符串 \\s*
-0+空格字符 "
-雙引號 ([^"]*)
-捕獲組#1:零個或多個除"
"
-雙引號。 C#演示 :
var test = "and ( [family]: \" trees \" or [family]: \" colors \" )";
var result = Regex.Matches(test, @"\[family]:\s*""([^""]*)""")
.Cast<Match>()
.Select(m => m.Groups[1].Value.Trim())
.ToList();
foreach (var s in result)
Console.WriteLine(s); // => trees, colors
如果要從字面上匹配[
,則必須對其進行轉義\\[
否則它將啟動一個字符類 。
獲得所需值的一種方法是使用正向后視 (<=
和正向前視(?=
:
說明
(?<=\\[family]: ")
正向后方斷言左側是[family]:
[^"]+
匹配不是一個"
使用一個或多個次否定的字符類 (?=")
正向前瞻,它斷言右側是"
例如:
string pattern = @"(?<=\[family]: "")[^""]+(?="")";
var test = "and ( [family]: \" trees \" or [family]: \" colors \" )";
foreach (Match m in Regex.Matches(test, pattern))
Console.WriteLine(m.Value.Trim());
這將導致:
trees
colors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.