我在下面得到了适用于单引号的代码。 它找到单引号之间的所有单词。 但是我如何修改正则表达式以使用双引号?
关键字来自表单帖子
所以
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)
}
答案 0 :(得分:17)
您只需将'
替换为\"
并删除文字即可正确重建。
MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\"");
答案 1 :(得分:10)
完全相同,但用双引号代替单引号。双引号在正则表达式模式中并不特殊。但我通常会添加一些内容以确保我不会在单个匹配中跨越多个引用的字符串,并且可以容纳双重双引号转义:
string pattern = @"""([^""]|"""")*""";
// or (same thing):
string pattern = "\"(^\"|\"\")*\"";
转换为文字字符串
"(^"|"")*"
答案 2 :(得分:4)
使用此正则表达式:
"(.*?)"
或
"([^"]*)"
在C#中:
var pattern = "\"(.*?)\"";
或
var pattern = "\"([^\"]*)\"";
答案 3 :(得分:2)
您要匹配"
还是'
?
在这种情况下,您可能希望执行以下操作:
[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);
}