आप एक regex का उपयोग करने के है, तो आप यह कर सकते हैं अगर आप यह सुनिश्चित करें कि सभी उद्धरण सही ढंग से संतुलित हैं, और कोई स्ट्रिंग में उद्धरण (\"
) भाग निकले देखते हैं अगर कर रहे हैं (यह उन के लिए खाते के लिए संभव है , भी, लेकिन यह regex और भी जटिल बनाता है)।
resultString = Regex.Replace(subjectString,
@"[\ ] # Match a space (brackets for legibility)
(?= # Assert that the string after the current position matches...
[^""]* # any non-quote characters
(?: # followed by...
""[^""]* # one quote, followed by 0+ non-quotes
""[^""]* # a second quote and 0+ non-quotes
)* # any number of times, ensuring an even number of quotes
$ # until the end of the string
) # End of lookahead",
"%", RegexOptions.IgnorePatternWhitespace);
यह वर्तमान अंतरिक्ष चरित्र के बाद उद्धरण के सम संख्या का दावा करने की स्ट्रिंग के शेष जांच करता है। लुकहेड का लाभ (धन्यवाद एलन मूर!) यह है कि यह दिखने से अधिक पोर्टेबल है (.NET को छोड़कर अधिकांश रेगेक्स स्वाद और कुछ अन्य लोग दृढ़ विश्वास के अंदर अनिश्चित पुनरावृत्ति का समर्थन नहीं करते हैं)। यह भी तेजी से हो सकता है।
मूल समाधान lookbehind से जुड़े इस प्रकार है:
resultString = Regex.Replace(subjectString,
@"(?<= # Assert that the string up to the current position matches...
^ # from the start of the string
[^""]* # any non-quote characters
(?: # followed by...
""[^""]* # one quote, followed by 0+ non-quotes
""[^""]* # a second quote and 0+ non-quotes
)* # any number of times, ensuring an even number of quotes
) # End of lookbehind
[ ] # Match a space (brackets for legibility)",
"%", RegexOptions.IgnorePatternWhitespace);
स्रोत
2011-05-24 14:38:08
@ एंड्रियास: अच्छी पसंद। आपको ओडेड के उत्तर को स्वीकार करना चाहिए, फिर (उसके बगल में स्थित चेकमार्क पर क्लिक करें)। –