Regex.Matches c# 双引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9133220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:07:00  来源:igfitidea点击:

Regex.Matches c# double quotes

c#.netregex

提问by user713813

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

采纳答案by Joel Etherton

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

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

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

回答by Joshua Honig

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

转换为文字字符串

"(^"|"")*"

回答by Kirill Polishchuk

Use this regex:

使用这个正则表达式:

"(.*?)"

or

或者

"([^"]*)"

In C#:

在 C# 中:

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

or

或者

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

回答by Sam Greenhalgh

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, @"(?<=([\'\""])).*?(?=)");
    Assert.AreEqual("this world", matches[0].Value);
    Assert.AreEqual("and then", matches[1].Value);
}