简体   繁体   English

正则表达式获取\\“和\\”之间的字符串

[英]Regex to get string between \“ and \”

As I am new to the regex, I would like to get help here. 由于我是正则表达式的新手,所以我想在这里获得帮助。

var test = "and ( [family]: \\" trees \\" or [family]: \\" colors \\" )" var test =“ and([[family]:\\”树木\\“或[family]:\\”颜色\\“)”

I would like to extract the family lists: 我想提取家庭名单:

trees 树木

colors 颜色

I used the following pattern. 我使用了以下模式。

Regex.Matches(test, @"[family]:\*\");

It is not working for me, Any suggestion would be helpful. 它对我不起作用,任何建议都将有所帮助。

You may use 您可以使用

Regex.Matches(filters.queryString, @"\[family]:\s*""([^""]*)""")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value.Trim())
    .ToList();

See the regex demo 正则表达式演示

The values you need are in Group 1, and with .Trim() , the leading/trailing whitespace gets removed from those substrings. 您需要的值在组1中,并且使用.Trim().Trim()前导/后缀空格从这些子字符串中删除。

Pattern details 图案细节

  • \\[family]: - a [family] substring \\[family]: - [family]子字符串
  • \\s* - 0+ whitespace chars \\s* -0+空格字符
  • " - a double quote " -双引号
  • ([^"]*) - Capturing group #1: zero or more chars other than " ([^"]*) -捕获组#1:零个或多个除"
  • " - a double quote. " -双引号。

C# demo : 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

If you want to match a [ literally, you have to escape it \\[ or else it would start a character class . 如果要从字面上匹配[ ,则必须对其进行转义\\[否则它将启动一个字符类

One way to get the values you are looking for is to use a positive lookbehind (<= and a positive lookahead (?= : 获得所需值的一种方法是使用正向后视 (<=和正向前视(?=

(?<=\\[family]: ")[^"]+(?=")

Explanation 说明

  • (?<=\\[family]: ") Positive lookbehind that asserts that what is on the left side is [family]: (?<=\\[family]: ")正向后方断言左侧是[family]:
  • [^"]+ Match not a " one or more times using a negated character class [^"]+匹配不是一个"使用一个或多个次否定的字符类
  • (?=") Positive lookahead that asserts that what is on the right side is a " (?=")正向前瞻,它断言右侧是"

For example: 例如:

string pattern = @"(?<=\[family]: "")[^""]+(?="")";
var test = "and ( [family]: \" trees \" or [family]: \" colors \" )";

foreach (Match m in Regex.Matches(test, pattern))
    Console.WriteLine(m.Value.Trim());

That will result in: 这将导致:

trees
colors

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM