Reputation: 1300
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 ?
Upvotes: 3
Views: 96
Reputation: 31841
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.
Upvotes: 2
Reputation: 6374
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.
Upvotes: 3