1

I have a Java bot that I'm working on which takes input from a user via an IRC message. The user types in something like .host file=foo file=bar hostname="this is a name" and it will start a server for them based on their input.

Right now I have a method that basically parses their message, looking for hostname="" (must be encapsulated by quotes), splitting the hostname= part, and setting the hostname to whatever their result is (for example, hostname="this is a name" would become -hostname 'this is a name'). I am using regex to do this.

I then split the string into an array (separated by spaces) and pass the information to processbuilder, which executes the command in it's own thread. The final command looks something like this:

./server -hostname "this is a name"

A problem I am running into is that since I am splitting by spaces, if the user adds a dash in the hostname (for example, hostname="this is - a name", it'll think that the dash is referring to an argument, and will basically chop off the rest.

Further explanation: processbuilder will split by spaces, so it will pass "-hostname" , "this" , "is" , "-" , "a" , "name". This is where I'm having trouble, since - means I should be passing an argument, but that's not what I am using it for.

What would be the most efficient way to implement this so that any character being passed is only literally this character? Should I not be splitting at spaces? If I run ./server -hostname "this is - a name" from the linux shell, it will run fine.

I appreciate any and all help. Thank you!

4

2 回答 2

3

Runtime.exec 和 ProcessBuilder 都将采用命令列表。

Runtime.exec(new String[]{"./server", "-hostname", "this is - a name"};
ProcessBuilder pb = new ProcessBuilder("./server", "-hostname", "this is - a name");

这基本上意味着每个元素都作为单独的参数传递给命令(第一个参数),这样您就不必担心空格和额外字符之类的事情。

于 2012-10-12T21:19:19.877 回答
0

我决定彻底改变我的代码并使用正则表达式来解析用户的输入,而不是以前的方法和空格分割。这意味着我可以简单地将输入作为完整的“+sv_hostname="test - name"”添加到 Arraylist,而不是使用“+sv_hostname”、“test”、“-”、“name”。

于 2012-10-13T01:28:57.343 回答