C # advanced String.Split

I have a line like this:

The boy told his mother: "Can I eat sweets?"

If I do a normal String.Split on it, I get:

 { 'The', 'boy', 'said', 'to', 'his', 'mother', '"Can', 'I', 'have', 'some', 'candy?"' } 

I need an array:

 { 'The', 'boy', 'said', 'to', 'his', 'mother', 'Can I have some candy?' } 

Obviously, I could just scroll the character by character and see if I am on the line or not, and all that ... but is there a better way? Using regular expressions?

+8
arrays split c #
source share
2 answers

How to find all matches of this regular expression:

 "[^"]*"|\S+ 
+9
source share

Depends on your requirements. For example. Do you need to treat AAA "BBB" (without spaces) as the word "slot" or two words? If AAA β€œBBB is one word,” and β€œonly after entering the Qouted field launches the Qouted field, it looks like a CSV parser. Other rules, like double qoutes, mean an alphabetic quote, etc., but you also need will define some similar rules.

So, you can adapt any open source CSV analyzer or see, for example, Microsoft.VisualBasic.FileIO.TextFieldParser works for you

  string msg = "The boy said to his mother, \"Can I have some candy?\""; System.IO.MemoryStream s = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(msg)); TextFieldParser p = new TextFieldParser(s, Encoding.Unicode); p.Delimiters = new string[] { " ", "," }; foreach(var f in p.ReadFields().Where(f => f != "")) Console.WriteLine(f); 
+2
source share

All Articles