Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a command line in Java

What's the recommended way to parse a shell-like command line in Java. By that I don't mean processing the options when they are already in array form (e.g. handling "-x" and such), there are loads of questions and answers about that already.

No, I mean the splitting of a full command string into "tokens". I need to convert a string such as:

user 123712378 suspend "They are \"bad guys\"" Or\ are\ they?

...to the list/array:

user
123712378
suspend
They are "bad guys"
Or are they?

I'm currently just doing a split on whitespace, but that obviously can't handle the quotes and escaped spaces.

(Quote handling is most important. Escaped spaces would be nice-to-have)

Note: My command string is the input from a shell-like web interface. It's not built from main(String[] args)

like image 567
Bart van Heukelom Avatar asked Aug 22 '26 04:08

Bart van Heukelom


1 Answers

ArgumentTokenizer from DrJava parses command line in a way Bourne shell and its derivatives do.

It properly supports escapes, so bash -c 'echo "\"escaped '\''single'\'' quote\""' gets tokenized into [bash, -c, echo "\"escaped 'single' quote\""].

like image 122
nvamelichev Avatar answered Aug 23 '26 19:08

nvamelichev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!