1
$\begingroup$

I'm trying to add quotation marks to the elements of a list which happens to be a single string separated by commas and line breaks, to then split the string at the commas respecting line breaks.

Assume we have a string like this:

string = "a,b,c,d
         e,f,g,h"

Since the string contains a single element, to add quotations I've tried adding " around the commas and after the line breaks, with StringReplace[string, {"," -> "\",\"", "\n" -> "\"\n"}], but the result is not quite what I expect:

"a","b","c","d"
         e","f","g","h"

How can I add quotations to all elements separated by commas, including these at the beginning of a line or at a line break? The result being something like:

"a","b","c","d"
"e","f","g","h"

Additionally, how can we split the string at each comma (,) while respecting the line breaks?

If we do split = StringSplit[string, ","], the result is weird:

a,b,c,d
         e,f,g,h

Specifically, d and e becomes a single element, with the line break added to it:

split[[4]]

"d
         e"

Thanks

$\endgroup$
1
$\begingroup$
StringReplace[string, {
  StartOfString -> "\"",
  "," -> "\",\"",
  patt : ("\n" ~~ WhitespaceCharacter ..) :> StringJoin["\"", patt, "\""],
  EndOfString -> "\""}]
"a","b","c","d"
          "e","f","g","h"

or without the brackets

StringReplace[string, {
  StartOfString -> "\"",
  "," -> "\",\"",
  patt : "\n" ~~ WhitespaceCharacter .. :> StringJoin["\"", patt, "\""],
  EndOfString -> "\""}]
"a","b","c","d"
"e","f","g","h"

And for splitting the string

Flatten[Fold[StringSplit, string, {",", "\n"}]]
{a, b, c, d,          e, f, g, h}

or

Flatten[Fold[StringSplit, string, {",", "\n" ~~ WhitespaceCharacter ..}]]
{a, b, c, d, e, f, g, h}

Additional case

string = "two words, one\n     another, this three words"

StringRiffle[
 StringReplace[#, {StartOfString -> "\"", "," -> "\",\"", 
     patt : ("\n" ~~ WhitespaceCharacter ..) :> 
      StringJoin["\"", patt, "\""], EndOfString -> "\""}] & /@ 
  StringTrim /@ StringSplit[string, ","], ","]
"two words", "one"
     "another", "this three words"
| improve this answer | |
$\endgroup$
  • $\begingroup$ Interesting. It works for the case I gave and most cases I've tested, but it seems to rely on white spaces, which is problematic for many cases I work with, in which I have things like "two words, one, this three words", etc. In particular, it adds line breaks at white spaces. $\endgroup$ – TumbiSapichu Mar 14 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.