user713813
user713813

Reputation: 785

Regex.Matches c# double quotes

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)
    }

Upvotes: 23

Views: 87250

Answers (4)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

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);
}

Upvotes: 6

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use this regex:

"(.*?)"

or

"([^"]*)"

In C#:

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

or

var pattern = "\"([^\"]*)\"";

Upvotes: 7

Joshua Honig
Joshua Honig

Reputation: 13215

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

"(^"|"")*"

Upvotes: 14

Joel Etherton
Joel Etherton

Reputation: 37533

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

MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\"");

Upvotes: 26

Related Questions