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
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
+2
source to share