简体   繁体   中英

Regular Expression advice for [Alphanumeric][alphanumeric.-_@] 31 characters

I'm looking to do a name check using regex in javascript.

  1. The value can contain alphanumeric and following special characters ('-', '.' '_' and '@').
  2. It should always start with an alphanumeric character.
  3. It should not be an empty string.
  4. Maximum allowed length for this parameter is 31 characters.
  5. This parameter is case-insensitive.

I came up with this, but feel it's incorrect. Any advice on how to have it foolproof?

^[A-Za-z0-9]+[A-Za-z0-9_@-.]{30}

You are quite close, here is the corrected regex:

/^[a-z0-9][\w@.-]{0,30}$/i

I applied the folloing changes:

  • Added $ anchor to the end
  • used the i-modifier for case-insensitivity
  • replaced a-zA-Z0-9_ with \\w and moved - to the end of the character class
  • changed fixed repetition {30} to {0,30}

See the Regex101-Demo with some unit tests.

^[A-Za-z0-9][A-Za-z0-9_@.-]{0,30}
  • place - at the and of brackets, so it won't be used as a range
  • allow 1-31 characters {,30}
  • remove + after first character (without it you would get >31 chars)

You can always check your patterns at www.regexr.com

  • You need to escape the '-' with and backslash like this: \\- .
  • You need to remove the + in the middle part
  • Change {30} to {0,30} because it doesn't need to be exactly 31 characters long
  • Add \\i to the end for case insensitive and remove the AZ parts
  • Close the pattern with $

Result looks like this:

/[a-z0-9][a-z0-9@\-._]{0,30}/i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM