18

I got this code below that works for single quotes. it finds all the words between the single quotes. but how would I modify the regex to work with double quotes?

keywords is coming from a form post

so

keywords = 'peace "this world" would be "and then" some'


    // Match all quoted fields
    MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");

    // Copy groups to a string[] array
    string[] fields = new string[col.Count];
    for (int i = 0; i < fields.Length; i++)
    {
        fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
    }// Match all quoted fields
    MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");

    // Copy groups to a string[] array
    string[] fields = new string[col.Count];
    for (int i = 0; i < fields.Length; i++)
    {
        fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
    }
Kirill Polishchuk
  • 51,053
  • 10
  • 118
  • 119
user713813
  • 691
  • 1
  • 8
  • 18

4 Answers4

23

You would simply replace the ' with \" and remove the literal to reconstruct it properly.

MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\"");
Joel Etherton
  • 36,043
  • 10
  • 81
  • 99
11

The exact same, but with double quotes in place of single quotes. Double quotes aren't special in a regex pattern. But I usually add something to make sure I'm not spanning accross multiple quoted strings in a single match, and to accomodate double-double quote escapes:

string pattern = @"""([^""]|"""")*""";
// or (same thing):
string pattern = "\"(^\"|\"\")*\"";

Which translates to the literal string

"(^"|"")*"
Joshua Honig
  • 12,125
  • 7
  • 47
  • 71
6

Use this regex:

"(.*?)"

or

"([^"]*)"

In C#:

var pattern = "\"(.*?)\"";

or

var pattern = "\"([^\"]*)\"";
Kirill Polishchuk
  • 51,053
  • 10
  • 118
  • 119
3

Do you want to match " or ' ?

in which case you might want to do something like this:

[Test]
public void Test()
{
    string input = "peace \"this world\" would be 'and then' some";
    MatchCollection matches = Regex.Matches(input, @"(?<=([\'\""])).*?(?=\1)");
    Assert.AreEqual("this world", matches[0].Value);
    Assert.AreEqual("and then", matches[1].Value);
}
Sam Greenhalgh
  • 5,514
  • 18
  • 36