2012-02-03 18 views
6

मुझे यह कोड नीचे दिया गया है जो सिंगल कोट्स के लिए काम करता है। यह एकल उद्धरण के बीच सभी शब्द पाता है। लेकिन मैं डबल कोट्स के साथ काम करने के लिए रेगेक्स को कैसे संशोधित करूं?Regex.Matchches सी # डबल कोट्स

कीवर्ड एक रूप पद

से आ रही है तो

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

यह स्ट्रिंग में उद्धरण डाल करने के लिए काम नहीं करेंगे:

जिस स्थिति में आप इस तरह कुछ करने के लिए चाहते हो सकता है? @ -स्ट्रिंग्स उद्धरण के लिए \ "के बजाय \" उपयोग करते हैं। "@" "(। *?)" "" –

उत्तर

13

आप बस \" साथ ' की जगह और यह ठीक से फिर से संगठित करने शाब्दिक को दूर करेंगे।

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

रेगेक्स में बचने की कोई आवश्यकता नहीं है। –

+0

प्रीफेक्ट। और अगर मैं स्ट्रिंग में उद्धरण शामिल करना चाहता था? – user713813

+0

@ user713813: स्ट्रिंग के संबंधित सिरों पर ब्रैकेट्स (साथ ही _nongreedy_ चिह्न) को ले जाएं। – Nuffin

8

सटीक वही है, लेकिन सिंगल कोट्स के स्थान पर डबल कोट्स के साथ। डबल कोट्स रेगेक्स पैटर्न में विशेष नहीं हैं। लेकिन मैं आमतौर पर यकीन है कि मैं एक ही मैच में कई उद्धृत तार करवाते फैले नहीं कर रहा हूँ बनाने के लिए कुछ जोड़ने, और डबल दोहरे उद्धरण समायोजित करने के लिए निकल जाता है:

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

कौन सा शाब्दिक स्ट्रिंग

"(^"|"")*" 
3
करने के लिए अनुवाद

"(.*?)" 

या

"([^"]*)" 
:

इस regex का उपयोग

सी # में:

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); 
} 
संबंधित मुद्दे