在Java中分割命令行 [英] Splitting a command line in Java

查看:94
本文介绍了在Java中分割命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中解析类似于shell的命令行的推荐方法是什么?因此,我并不是说要处理已经为数组形式的选项(例如,处理"-x"之类的东西),已经有很多关于此的问题和答案了.

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)

注意:我的命令字符串是类似Shell的Web界面的输入.它不是从main(String[] args)

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

推荐答案

您需要实现的是有限自动机.您需要逐个字符地读取字符串,并根据您的下一个或上一个字符找到下一个状态.
例如,"表示字符串的开头,但是如果在其前面加上\,则将保持当前状态不变,并读取直到下一个标记将您带到下一个状态.
IE.本质上,在您的示例中,您将拥有

What you would need is to implement a finite automaton. You would need to read the string character by character and find the next state depending on your next or previous character.
For example a " indicates start of a string but if it is preceded by an \ leaves the current state unchanged and reads until the next token that takes you to the next state.
I.e. essentially in your example you would have

read string -> read number   
      ^  -    -   -  |  

您当然需要定义所有状态以及影响或不影响您状态的特殊字符.
老实说,我不确定您为什么要向最终用户提供此类功能.
传统上,所有cli程序都接受标准格式-x or --x or --x=s等的输入.
这种格式对于一般用户来说是众所周知的,并且易于实现和正确测试.
传统上,如果需要我们为用户提供更多灵活"的输入,则最好构建一个GUI.这就是我的建议.

You of course would need to define all the states and the special characters that affect or not affect your state.
To be honest I am not sure why you would want to provide such functionality to the end user.
Traditionally all the cli programs accept input in a standard format -x or --x or --x=s etc.
This format is well known to a typical user and is simple to implement and test as correct.
Traditionally if we are required to provide more "flexible" input for the user, it is best to build a GUI. That is what I would suggest.

这篇关于在Java中分割命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆