2012-02-03 18 views
6

Ho ottenuto questo codice di seguito che funziona per le virgolette singole. trova tutte le parole tra le virgolette singole. ma come modifico la regex per lavorare con virgolette doppie?Regex.Matches C# doppie virgolette

parole chiave è proveniente da un formulario posta

così

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

Non sarebbe lavorare per mettere le virgolette nella stringa? @ -strings usa "" invece di \ "per le virgolette.' @ "" "(. *?)" "" ' –

risposta

13

Si potrebbe semplicemente sostituire il ' con \" e rimuovere il letterale di ricostruire in modo corretto.

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

Non c'è bisogno di sfuggire' "' nell'espressione regolare. –

+0

prefetto. e se volessi includere le virgolette nella stringa? – user713813

+0

@ user713813: sposta le parentesi (come pure il segno _nongreedy_) alle rispettive estremità della stringa. – Nuffin

8

Le virgolette esattamente lo stesso, ma con al posto di singoli apici. Le virgolette non sono speciali in un modello regex. Ma io di solito aggiungere qualcosa per assicurarsi che non mi si estende attraversato più stringhe citato in una singola partita, e per accogliere doppia-doppia citazione sfugge:

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

che si traduce la stringa letterale

"(^"|"")*" 
3

Utilizzare questa espressione regolare:

"(.*?)" 

o

"([^"]*)" 

In C#:

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

o

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

Volete abbinare " o '?

, nel qual caso si potrebbe desiderare di fare qualcosa di simile:

[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); 
} 
Problemi correlati