Aishwarya Shiva
Aishwarya Shiva

Reputation: 3406

Unable to extract string between double quotes using regex

I am trying to extract those substrings that are enclosed in double quotes using regular expression:

"\w[\w\s\t]*"

on string:

"@test" skip "2 3" skip "TEST" skip "te st" skip "@#"

Bolded substrings are successfully extracted. But those with special characters are not extracted. Please help me solve this. I am not so pro in making regular expressions.

Upvotes: 2

Views: 2897

Answers (4)

Kyle W
Kyle W

Reputation: 3752

As eckes said in his comment, try using

"[^"]*"

This should match a quote, then any number of characters that aren't quotes, then another quote. The other answers will not match a 0-length, depending on if that's what you want.

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can also match a substring containing escaped double quotes:

Regex: ".+?(?<!\\)"

Code:

var txt1 = "\"This is \\\"some text\\\" to capture\" \"no other text\"";
var regex1 = new Regex(@""".+?(?<!\\)""", RegexOptions.IgnoreCase  | RegexOptions.CultureInvariant);
var c1 = regex1.Matches(txt1).Cast<Match>().Select(d => d.Value.Trim()).ToList();

Output:

"This is \"some text\" to capture"
"no other text"

Upvotes: 2

apgp88
apgp88

Reputation: 985

This regex should work

"(.+?)"

Regex101 demo

It uses the concept of Group capture

Upvotes: 3

EZI
EZI

Reputation: 15364

string input = @"""@test"" skip ""2 3"" skip ""TEST"" skip ""te st"" skip ""@#""";
var values = Regex.Matches(input, @"\""(.+?)\""")
                  .Cast<Match>()
                  .Select(m => m.Groups[1].Value)
                  .ToList();

Upvotes: 1

Related Questions