Splitting Java into space using regexp?

I am trying to match and grab command and parameters from the following input:

!command param1 param2

      

I am using Java classes Pattern

and Matcher

:

private Pattern regExp = Pattern.compile(
        "^!(?<command>[^\\s]*)((?:\\s+)(?<param>[^\\s]*))*$");

public String command() {
    m = regExp.matcher(getMsg());
    return m.matches() ? m.group("command") : "";
}

public String param(int index) {
    return m.group(index);
}

      

also using this ( http://fiddle.re/yanta6 ) to experiment ....

some pointer and help is appreciated!

+3


source to share


2 answers


Personally, I wouldn't use a regex for this. If your input

!command param1 param2 paramX

      



Then normal string manipulation would do the job nicely. Just drop the opening! and then use the split by ""

+5


source


You can do this with a regular expression.

Pattern pattern = Pattern.compile("(?:^!(?<Command>\\S+)|)\\s+(?<params>\\S+)");
String input = "!command param1 param2 param3 paramn param3 param4";
Matcher matcher = pattern.matcher(input);
while(matcher.find())
{
    if(matcher.group("Command") != null)
    {
    System.out.println(matcher.group("Command"));
    }
    if(matcher.group("params") != null)

    System.out.println(matcher.group("params"));
}

      

Output:



command
param1
param2
param3
paramn
param3
param4

      

DEMO

+2


source







All Articles