Reputation: 289
Mainly I am using regex, and what my code does essentially, is sends a client return code if it does not contain the characters in regex. My problem is, I do not know how to allow spaces. Currently this is my code, I would like to have allow a space, a-z, A-Z and 0-9.
if (username.length() < 1 || username.length() >= 13
|| !username.matches("[a-zA-Z_0-9]"))
{
session.getLoginPackets().sendClientPacket(3);
return;
}
Upvotes: 1
Views: 1038
Reputation: 7361
use the \w metasequence (words, letters, underscores), plus a space (or \s to match tabs too), in a character class:
var pattern = @"[\w ]{1,12}"; //c#, validates length also.
edit: this seems to work for single spacing only, does not validate the length though:
var pattern = @"^(\w+\s?)+$";
Upvotes: 2
Reputation: 93086
I am quite sure you want to be Unicode compliant, so you should use
[\p{L}\p{Nd}][\p{L}\p{Nd} ]*
I created two character classes to ensure that it is not starting with a space, if this check is not needed, just remove the first class and change the quantifier of the second to a +
.
\p{Nd} or \p{Decimal_Digit_Number}: a digit zero through nine in any script except ideographic scripts.
\p{L} or \p{Letter}: any kind of letter from any language.
Upvotes: 2
Reputation: 33
Try this one
if (username.length() < 1 || username.length() >= 13
|| !username.matches("[a-zA-Z0-9 ]+"))
{
session.getLoginPackets().sendClientPacket(3);
return;
}
Upvotes: 1
Reputation: 12581
The regex you're looking for is [a-zA-Z_0-9][a-zA-Z_0-9 ]*
assuming you don't want a name to start with spaces.
Upvotes: 2