tags:

views:

78

answers:

2

I want to restrict input to match the statement change = where word and value are both arbitrary words (sequences of characters that don't include spaces) and only one space exists (between the word "change" and a) in the input.

For example, "change variable=value" is valid but "change variable= value" and "change this" are not.

My attempt:

  private static final Pattern SET = Pattern.compile("change\\s\\w=\\w");

I use the clause

  if(SET.matcher(command).find())
  {
     ...
  }

to check for proper output but haven't been able to get the function to work properly. Where am I going wrong? What syntax should I use for this particular regular expression? (Please let me know if further clarification is needed)

+3  A: 

This matches what you requested. String which exactly start witch "change" followed by a single space. Then a word followed by an equal sign followed by another word. Then end of string

private static final Pattern SET = Pattern.compile("^change \\w+=\\w+$");
jitter
An alternative would be to use the `matches` method instead of `find`.
Jörn Horstmann
With this special regex there shouldn't be a difference. If you leave the start and end regex symbols out, you got a point
jitter
This worked great. Thanks so much!
synchronicity
A: 

First thing, you need to change your regexp to: (I went ahead an assumed whitespace didn't matter. Remove the \s* if this isn't the case)

SET = Pattern.compile("\\s*change\\s+\\w+\\s*=\\s*\\w+\\s*");

The \w match needs a '+' on it to match 1 or more characters in [0-9_A-Za-z]. Otherwise it looks for exactly one of [0-9_A-Za-z].

KitsuneYMG
He explicitly states that between change and the key=value he only wants 1 space
jitter