简体   繁体   中英

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

您只需替换' with \\"并删除文字即可正确重建它。

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

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

"(^"|"")*"

Use this regex:

"(.*?)"

or

"([^"]*)"

In C#:

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

or

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

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

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