I am confused about how Read separates elements.

The following all work fine:

str = StringToStream["123 xyz 456"];
Read[str, {Number, Word, Number}, RecordSeparators -> {" ", "\t"}]
(* {123, "xyz", 456} *)
str = StringToStream["asd, xyz"];
Read[str, {Word, Word}, WordSeparators -> {" ", "\t", ","}]
(* {"asd", "xyz"} *)
str = StringToStream["123xyz"];
Read[str, Number]
(* 123 *)

Why does this not work? And how would I handle this input with Read, without reading in a full line as a string and post-processing it? Is it at all possible?

str = StringToStream["123, xyz, 456"];
Read[str, {Number, Word, Number}, WordSeparators -> {" ", "\t", ","}]

During evaluation of Read::readn: Invalid real number found when reading from StringToStream[123, xyz, 456].
(* $Failed *)
  • 1
    $\begingroup$ it seems after reading the Word the comma is left on the stream and throws the error. This "works" Read[str, {Number, Word, Character, Number}, WordSeparators -> {" ", ","}]. Not satisfactory but it gives a clue whats happening. $\endgroup$ – george2079 Apr 11 '17 at 14:17
  • $\begingroup$ @george2079 I know this issue (what you describe) has come up before. Do you recall another question like this? $\endgroup$ – Mr.Wizard Apr 11 '17 at 14:29
  • $\begingroup$ Okay, I think this issue is covered here: (17841) but I need to re-read it to be sure. Edit: Yes, it is covered there. Szabolcs, @george do you think this deserves a separate question? $\endgroup$ – Mr.Wizard Apr 11 '17 at 14:33
  • 1
    $\begingroup$ I think we can call it a dup. The short synopsis being the Number type does not utilize/respect the separator options. You can see that just like this : Read[StringToStream["1,2"], {Number, Number}, RecordSeparators -> {","}] $\endgroup$ – george2079 Apr 11 '17 at 14:51
  • $\begingroup$ Well I'm tentatively marking this as a duplicate as it looks like one to me. As always if you disagree please let me know! $\endgroup$ – Mr.Wizard Apr 11 '17 at 14:59

Browse other questions tagged or ask your own question.