Split string with quotes, reusing method that parses arguments to main
in small program I'm writing, I have to parse a line of user input. Basically what needs to be done is to split the line into an array of strings in the same way as is done with the arguments to main(), ie I'm looking for something like this:
String[] splitArgs(String cmdLine);
I just wonder, if the main methods' arguments are parsed in this way prior to invoking main itself, wouldn't it be possible to call that one instead of writing your own? So, does anyone know wher开发者_如何学编程e to find that method?
Thanks, Axel
On globbing
Command line argument is parsed by the shell; this is why *
is usually expanded to a list of files, for example. This is called "globbing", and it happens outside of your program, before the JVM even starts.
See also
- Wikipedia/Glob
Related questions
- Problem of * in Command line argument
On splitting strings
As for splitting strings into array of strings, your most basic option is String.split(String regex)
.
Here's a very simple example:
String[] parts = "one two three".split(" ");
for (String part : parts) {
System.out.println("[" + part + "]");
}
The above prints:
[one]
[two]
[three]
The String
argument to split
is a regular expression.
References
- regular-expressions.info
java.lang.regex.Pattern
Scanner
option
Another option you can use is java.util.Scanner
. This is a much more improved version of the legacy StringTokenizer
.
Related questions
- Split/tokenize/scan a string being aware of quotation marks
- Example of using
Scanner
that is aware of simple quotes
- Example of using
- Scanner vs. StringTokenizer vs. String.Split
- Validating input using java.util.Scanner
- Many examples on validating numbers, vowels, etc
Guava option
For a more powerful String
splitting functionality, you can use e.g. Splitter
from Guava.
No, that parsing is done by the shell or system library (on Windows), not by Java. You could use ProcessBuilder and sh -c (or cmd on Windows). Something like:
new ProcessBuilder("sh", "-c", "java Program " + cmdLine).start();
I just found another way by apache commons exec to fix this.
public static String[] splitArgsStr(String argsStr) {
org.apache.commons.exec.CommandLine execCommandLine = new org.apache.commons.exec.CommandLine("sh");
execCommandLine.addArguments(argsStr, false);
return execCommandLine.getArguments();
}
And the latest maven dependency is:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
That sort of parsing is usually done by the shell. So the function you're looking for would be part of a completely separate program, which is probably written in C. By the time the Java VM even gets started, the arguments have already been parsed.
精彩评论