Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: C# extract text within double quotes

Tags:

c#

regex

I want to extract only those words within double quotes. So, if the content is:

Would "you" like to have responses to your "questions" sent to you via email?

The answer must be

  1. you
  2. questions
like image 949
new_linux_user Avatar asked Oct 23 '12 05:10

new_linux_user


People also ask

Does C have regex?

The expression can be used for searching text and validating input. Remember, a regular expression is not the property of a particular language. POSIX is a well-known library used for regular expressions in C.

Is regex a standard library in C?

C++11 now finally does have a standard regex library - std::regex.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is pattern matching in C language?

Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed.


2 Answers

Try this regex:

\"[^\"]*\" 

or

\".*?\" 

explain :

[^ character_group ]

Negation: Matches any single character that is not in character_group.

*?

Matches the previous element zero or more times, but as few times as possible.

and a sample code:

foreach(Match match in Regex.Matches(inputString, "\"([^\"]*)\""))     Console.WriteLine(match.ToString());  //or in LINQ var result = from Match match in Regex.Matches(line, "\"([^\"]*)\"")               select match.ToString(); 
like image 50
Ria Avatar answered Oct 06 '22 01:10

Ria


Based on @Ria 's answer:

static void Main(string[] args) {     string str = "Would \"you\" like to have responses to your \"questions\" sent to you via email?";     var reg = new Regex("\".*?\"");     var matches = reg.Matches(str);     foreach (var item in matches)     {         Console.WriteLine(item.ToString());     } } 

The output is:

"you" "questions" 

You can use string.TrimStart() and string.TrimEnd() to remove double quotes if you don't want it.

like image 32
Edi Wang Avatar answered Oct 06 '22 01:10

Edi Wang