Regular expressions: extract all words from quotes

Using regular expressions, how can I extract all the text in double quotes and all the words from the quotes in a line like this:

01AB "SET 001" IN SET "BACK" 09SS 76 "01 IN" SET 

The first regular expression should extract all text inside double quotes, e.g.

 SET 001 BACK 01 IN 

The second shoud expression extracts all other words in the string

 01AB IN SET 09SS 76 SET 

In the first case, it works fine ("(.*?)") . How to extract all words from quotes?

+6
source share
5 answers

Try the following expression:

 (?:^|")([^"]*)(?:$|") 

Groups matching it will exclude quotation marks because they are enclosed in non-capturing parentheses (?: And ) . Of course, you need to avoid double quotes for use in C # code.

If the target line begins and / or ends in a quotation value, this expression will also correspond to empty groups (for the initial and final quotes).

+5
source

Try this regex:

 \"[^\"]*\" 

Use Regex.Matches for double-quoted texts and use Regex.Split for all other words:

 var strInput = "01AB \"SET 001\" IN SET \"BACK\" 09SS 76 \"01 IN\" SET"; var otherWords = Regex.Split(strInput, "\"[^\"]*\""); 
+4
source

Perhaps you can try replacing the words inside the quotes with an empty string, for example:

 Regex r = new Regex("\".*?\"", RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.Singleline); string p = "01AB \"SET 001\" IN SET \"BACK\" 09SS 76 \"01 IN\" SET"; Console.Write(r.Replace(p, "").Replace(" "," ")); 
+2
source

You need to collapse the pattern in your first expression.

(?! pattern)

Check this link .

+1
source

If you are offered all the blocks of the sentence - quotation marks, rather than one, then there is an easier way to split the original string using Regex. Share :

 static Regex QuotedTextRegex = new Regex(@"("".*?"")", RegexOptions.IgnoreCase | RegexOptions.Compiled); var result = QuotedTextRegex .Split(sourceString) .Select(v => new { value = v, isQuoted = v.Length > 0 && v[0] == '\"' }); 
+1
source

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


All Articles