3

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

!command param1 param2

I am using Java's 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 appreciated!

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • So what's your question? Your pattern looks ok. – aioobe Dec 22 '14 at 11:37
  • 2
    Your title says "split on space". Did you try splitting on spaces? As for your question, you can only capture the last ``. This question is probably a duplicate: [Regular Expression - Capturing all repeating groups](http://stackoverflow.com/q/6835970/7586) – Kobi Dec 22 '14 at 11:39
  • 1
    Note that you can't have a variable number of capture groups: http://stackoverflow.com/questions/5018487/regular-expression-with-variable-number-of-groups You would have to match the entire params substring, and then split that match on space or whatever. – aioobe Dec 22 '14 at 11:41
  • https://regex101.com/r/nQ9gW0/1 – msrd0 Dec 22 '14 at 11:47
  • @karl What's your expected output? You could do this through only regex... – Avinash Raj Dec 22 '14 at 12:05

2 Answers2

5

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

!command param1 param2 paramX

Then normal string manipulation would do the job nicely. Just discard the opening ! and then use a split on " "

tddmonkey
  • 20,798
  • 10
  • 58
  • 67
2

You could do this through regex..

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

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274