简体   繁体   中英

Parsing arguments with double quotes

I am coding a client in Minecraft and have a command manager that accepts commands with arguments separated by spaces, such as $command arg1 arg2 arg3 .

// Message will output like "$command arg1 arg2" etc.
public void runCommand(String message) {
    String[] args = parseArgs(message);
}

// Accepts string, outputs array of arguments
public String[] parseArgs(String message) {
    return message.split(" ");
}

I have tried using the str.split(" ") function to seperate arguments by a space. However, the problem is when I have arguments surrounded in double quotes such as $command "This is an argument" , the function returns an array such as [$command, "This, is, an, argument"] .

How can I parse these arguments so that it outputs [$command, "This is an argument"] ?

Try this.

static final Pattern ARG_PAT = Pattern.compile("\"[^\"]+\"|\\S+");

public static String[] parseArgs(String message) {
    return ARG_PAT.matcher(message)
        .results()
        .map(r -> r.group())
        .toArray(String[]::new);
}

This is a job for regex!

There is a good general tutorial about regex in java here: https://www.vogella.com/tutorials/JavaRegularExpressions/article.html

For your case, I would suggest something like the following (code has not been tested) :

Pattern pattern = Pattern.compile("(\\S+) |(\".+\")";
        // one or more non-whitespace characters or quotes around one or more characters
        Matcher matcher = pattern.matcher(message);
        // check all occurance
        while (matcher.find()) {
                String arg = matcher.group();
                // add it to an array 
        }

Or you could probably do this with a for loop over the characters in a string, but regex is the nice way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM