Regex.Matches C# 双引号

23
我有以下可用于单引号的代码。 它可以找到所有在单引号之间的单词。 但是我该如何修改正则表达式以适应双引号呢?
关键字来自表单提交。
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)
    }

3
把引号放在字符串中不可以吗?@-字符串使用""代替"表示引号。@"""(.*?)""" - Kendall Frey
4个回答

26

你只需要用\"替换'并删除literal即可正确重构。

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

在正则表达式中,不需要转义 " - Kirill Polishchuk
完美。如果我想在字符串中包含引号呢? - user713813
@user713813:将括号(以及 nongreedy 标记)移动到字符串的相应末尾。 - Nuffin
根据 https://regex101.com/,在 C#/.NET 中需要使用""(两个连续的双引号)来匹配一个单个双引号。与Python不同,Python只需用反斜杠转义双引号。 - domjancik
感谢 @domjancik 的现代化更新。当这个问题在2012年回答时,反斜杠转义字符是首选的方法。我记得当时只有在VB.Net中双引号才能正常工作,但我可能记错了。 - Joel Etherton

13

完全相同,但双引号代替单引号。在正则表达式模式中,双引号并不特殊。但我通常添加一些内容以确保单个匹配不跨越多个带引号的字符串,并适应双倍双引号转义:

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

这意味着直译成字符串的内容

"(^"|"")*"

7
使用这个正则表达式:
"(.*?)"

或者

"([^"]*)"

在C#中:

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

或者

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

6

你想匹配双引号"还是单引号'

如果是这种情况,你可能希望像这样做:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接