InDaPond InDaPond - 1 year ago 120
Java Question

Check a String for several regex and say which one matched

First of all I know there are already thousands of RegEx posts, sadly my google/stackoverflow search skills didn't help to find what I was looking for.

I have a Server client communication. The client awaits a user's input.
Then he sends it to the server and the server checks if it is a valid command.

Pattern lowercase = Pattern.compile("LOWERCASE.*");
Pattern uppercase = Pattern.compile("UPPERCASE.*");
Pattern reverse = Pattern.compile("REVERSE.*");
Pattern bye = Pattern.compile("BYE");
Pattern shutdown = Pattern.compile("SHUTDOWN");

If it starts with one of those commands, do a certain action.
I have problems creating a Matcher that checks for several patterns and then I want to go into something like

Matcher.matches(uppercase|reverse|bye|...) //Is this how I do it?
case(lowercase): do something
case(reverse): do something else

and so on.
I hope my request is understandable.
And there will be multiple clients talking to the server, in case this is relevant for the answer(like Threading and static Patterns dont work well or sth)

Thank you.

Answer Source

You do it pattern-by-pattern, and use an if instead of switch:

if (lowercase.matcher(inputStr).find()) {
    ... // Do something
} else if (reverse.matcher(inputStr).find()) {
    ... // Do something else
} else {

You can combine all patterns into one, and use capturing groups instead:

Pattern all = Pattern.compile(
Matcher m = all.matcher(inputStr);
if (m.find()) {
    String upper ="upper");
    String lower ="lower");
    String reverse ="reverse");
    if (upper != null) {
        ... // Do something
    if (lower != null) {
        ... // Do something
    if (reverse != null) {
        ... // Do something

Note that the code above uses named capturing groups (<upper>, <lower>, etc.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download