Regex.Matches C # double quotes

I got this code below, which works for single quotes. it finds all words between single quotes. but how do I change the regex to work with double quotes?

keywords come from a form message

So

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) } 
+6
source share
4 answers

You just replace ' with \" and delete the literal to restore it correctly.

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

Same thing, but with double quotes instead of single quotes. Double quotes are not special in the regular expression pattern. But I usually add something to make sure that I do not span multiple lines with a line in one match and do not interfere with double double quotes:

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

What translates to a literal string

 "(^"|"")*" 
+8
source

Use this regex:

 "(.*?)" 

or

 "([^"]*)" 

In C #:

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

or

 var pattern = "\"([^\"]*)\""; 
+3
source

Do you want to combine " or ' ?

and in this case you can do something like this:

 [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); } 
+2
source

Source: https://habr.com/ru/post/907600/


All Articles