Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Matches c# double quotes

Tags:

I got this code below that works for single quotes. it finds all the words between the single quotes. but how would I modify the regex to work with double quotes?

keywords is coming from a form post

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)     } 
like image 703
user713813 Avatar asked Feb 03 '12 17:02

user713813


People also ask

Can I use regex in C?

There is no built-in support for regex in ANSI C.

How do I find regex matches?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does regex IsMatch return?

IsMatch(ReadOnlySpan<Char>, String, RegexOptions, TimeSpan) Indicates whether the specified regular expression finds a match in the specified input span, using the specified matching options and time-out interval.


2 Answers

You would simply replace the ' with \" and remove the literal to reconstruct it properly.

MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\""); 
like image 189
Joel Etherton Avatar answered Sep 21 '22 05:09

Joel Etherton


The exact same, but with double quotes in place of single quotes. Double quotes aren't special in a regex pattern. But I usually add something to make sure I'm not spanning accross multiple quoted strings in a single match, and to accomodate double-double quote escapes:

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

Which translates to the literal string

"(^"|"")*" 
like image 23
Joshua Honig Avatar answered Sep 23 '22 05:09

Joshua Honig