2012-02-03 30 views
6

我得到了下面的代码,适用于单引号。它找到单引号之间的所有单词。 但我将如何修改正则表达式使用双引号?Regex.Matches c#双引号

关键字是从表单POST

来得这么

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

那不是工作,把引号括起来的吗? @字符串使用“”而不是\“作为引号。”@“”“(。*?)”“”' – 2012-02-03 18:01:00

回答

13

只需将取代'\"并删除文字,以适当地恢复它。

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

不需要在正则表达式中转义'“'。 – 2012-02-03 18:04:49

+0

知府。如果我想在字符串中加入引号? – user713813 2012-02-03 18:07:28

+0

@ user713813:将括号(以及_nongreedy_标记)移至字符串的相应端。 – Nuffin 2012-02-03 18:15:30

8

完全相同,但用双引号代替单引号。双引号在正则表达式中并不特殊。但我通常添加的东西,以确保我没有翻过跨越在一场比赛中多次引用的字符串,并以适应双双引号逃逸:

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

它转换为文字串

"(^"|"")*" 
3

使用此正则表达式:

"(.*?)" 

"([^"]*)" 

在C#:

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

var pattern = "\"([^\"]*)\""; 
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); 
}