Regex.匹配c#双引号
本文关键字:匹配 Regex | 更新日期: 2023-09-27 18:22:20
我在下面得到了适用于单引号的代码。它查找单引号之间的所有单词。但是我该如何修改regex以使用双引号呢?
关键字来自后的表单
所以
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)
}
您只需将'
替换为'"
,然后删除文字即可正确重建。
MatchCollection col = Regex.Matches(keywords, "'''"(.*?)'''"");
完全相同,但用双引号代替单引号。双引号在正则表达式模式中并不特殊。但我通常会添加一些内容,以确保我不会在一个匹配中跨越多个引用的字符串,并适应双引号转义:
string pattern = @"""([^""]|"""")*""";
// or (same thing):
string pattern = "'"(^'"|'"'")*'"";
翻译成文字字符串
"(^"|"")*"
使用此正则表达式:
"(.*?)"
或
"([^"]*)"
在C#中:
var pattern = "'"(.*?)'"";
或
var pattern = "'"([^'"]*)'"";
您想匹配"
还是'
?
在这种情况下,你可能想做这样的事情:
[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);
}