3

My server dev gave me a regex that he says is the requirement for user name. It is @"^\w+([\s-]\w+)*$"

I need help figuring out right Java expression for this. It is confusing since I need to put some escape characters to make compiler happy.

I am trying this. Please let me know if this is right :

Pattern p = Pattern.compile("^\\w+([\\s-]\\w+)*\\$", Pattern.CASE_INSENSITIVE);

   Matcher m = p.matcher(username);

   if ((username.length() < 3 ) || (m.find())) {
      log ("Invalid pattern"); 
      return false;
   }

Is this correct ?

2 Answers 2

3

The correct pattern is "^\\w+([\\s-]\\w+)*$".

$ denotes the end of the string, if you use \\$ it will force the string to have the char $ and that's not the intent.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. So, what is this regex actually saying ? I understand \w is a word. So, does it mean, a name will be [word] optional : - or space or * followed by another word ?
should john* be a valid name then ?
^ is the beginning of the string, that should have at least one (+) word char (\w -> a-z or 0-9) followed by zero or more (*) occurrences of a space char (\s) or a dash (-) followed by at least one (+) word char (\w).
thanks. So, john* (john followed by asterix) is invalid then ?
john* is invalid in your case.
2

In your regex

^\\w+([\\s-]\\w+)*\\$
                    ^

You don't have to escape this $. It is there to indicate End Of Line.

so the correct Regex would be:

^\\w+([\\s-]\\w+)*$

N.B.: However, you have to make sure that this $ sign doesn't represent $ literally. In that case you'd have to escape it, but I anticipate in that case it would be escaped in your source RegEx as well.

2 Comments

thanks for the additional clarification. The name didnt require an explicit dollar sign. I guess this is just a end marker of the name.
@techtinkerer ya. I think in that case you should use RegEx ^\\w+([\\s-]\\w+)*$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.