I wish to have have the following String
!cmd 45 90 "An argument" Another AndAnother "Another one in quotes"
to become an array of the following
{ "!cmd", "45", "90", "An argument", "Another", "AndAnother", "Another one in quotes" }
I tried
new StringTokenizer(cmd, "\"")
but this would return “Another” and “AndAnother as “Another AndAnother” which is not the desired effect.
Thanks.
EDIT:
I have changed the example yet again, this time I believe it explains the situation best although it is no different than the second example.
It’s much easier to use a
java.util.regex.Matcherand do afind()rather than any kind ofsplitin these kinds of scenario.That is, instead of defining the pattern for the delimiter between the tokens, you define the pattern for the tokens themselves.
Here’s an example:
The above prints (as seen on ideone.com):
The pattern is essentially:
There are 2 alternates:
Note that this does not handle escaped double quotes within quoted segments. If you need to do this, then the pattern becomes more complicated, but the
Matchersolution still works.References
See also
Appendix
Note that
StringTokenizeris a legacy class. It’s recommended to usejava.util.ScannerorString.split, or of coursejava.util.regex.Matcherfor most flexibility.Related questions