简体   繁体   中英

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 \\" )"

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.

Pattern details

  • \\[family]: - a [family] substring
  • \\s* - 0+ whitespace chars
  • " - a double quote
  • ([^"]*) - Capturing group #1: zero or more chars other than "
  • " - a double quote.

C# demo :

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]:
  • [^"]+ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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