2012-02-03 31 views
6

私はこの引用符をシングルクォートで使用できます。 シングルクォート間のすべての単語を検索します。 しかし、二重引用符で動作するように正規表現を変更するにはどうすればよいですか?Regex.Matches c#二重引用符

キーワードは

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

は、それが文字列に引用符を入れて動作しませんか? @ -stringsは、引用符に ""の代わりに ""を使用します。 '@" ""(。*?) "" " –

答えて

13

ので、フォームポストから

を来ているあなたは、単に\"'を交換し、それを適切に再構成するためにリテラルを削除します。

+0

正規表現で' ''をエスケープする必要はありません。 –

+0

所長。私は文字列に引用符を含める場合は? – user713813

+0

@ user713813:括弧(および_nongreedy_マーク)を文字列の両端に移動します。 – Nuffin

8

正確に同じですが、一重引用符の代わりに二重引用符を使用します。二重引用符は正規表現のパターンでは特別ではありません。しかし、私は通常、私はシングルマッチで複数の引用文字列accrossスパニングないよ確認するために何かを追加し、二重、二重引用符を収容するためにエスケープ:文字列リテラル

"(^"|"")*" 
3
に変換

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

"(.*?)" 

または

"([^"]*)" 

この正規表現を使用します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); 
} 
関連する問題