nop
nop

Reputation: 6359

Get variables from a Regex Expression

I'm trying to validate the following:

/w username message

Here is my regex expression:

if (input.toLowerCase().matches("^/w(\\s+)([0-9a-zA-Z].*)(\\s+)([0-9a-zA-Z ].*)$")) {
...

How do I get the username and the message as variables?

String username = ???
String message = ???

Upvotes: 0

Views: 37

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

Pattern pattern = Pattern.compile("^\\/w\\s+(?<username>\\w+)\\s+(?<message>.+)$");
Matcher matcher = pattern.matcher("/w username message");

if(matcher.matches()) {
    String username = matcher.group("username");
    String message = matcher.group("message");
}

www.regex101.com

Upvotes: 3

Related Questions