Saturday, February 19, 2011

Getting values between quotes

How can I get the value between quotes with an RegEx

for example I want to find all the parameters from the function test

<html>
   test("bla");
   print("foo");
   test("moo");
</html>

The result must be { "bla", "moo" }

From stackoverflow
  • edit: Removed old code and made a linq version...

        var array = (from Match m in Regex.Matches(inText, "\"\\w+?\"")
                     select m.Groups[0].Value).ToArray();
    
        string json = string.Format("{{{0}}}", string.Join(",", array));
    
  • If you just want the args to test, you'll need to include that in the regex:

        StringBuilder sb = new StringBuilder("{");
        bool first = true;
        foreach (Match match in Regex.Matches(html, @"test\((""[^\""]*\"")\)"))
        {
            if(first) {first = false;}
            else {sb.Append(',');}
            sb.Append(match.Groups[1].Value);
        }
        sb.Append('}');
        Console.WriteLine(sb);
    

    From the question, I am using quote detection here.

    Alternatively - if you just want the values:

        foreach (Match match in Regex.Matches(html, @"test\(""([^\""]*)\""\)"))
        {
            Console.WriteLine(match.Groups[1].Value);
        }
    

    The main change here is that the group is now inside the quotes.

0 comments:

Post a Comment