简体   繁体   中英

Regular Expression for Illegal first character

I have an input field that uses the HTML5 pattern attribute to only allow alphanumeric characters and underscores ^[a-zA-Z0-9_]+$ .

How do I adjust the code so that the string can't begin with an underscore character, yet still allow them within the remainder of the string?

Any help with this would be greatly appreciated!

Note: If my explanation above isn't clear, below is a list of valid / invalid input values.

  1. has_underscore valid
  2. _begins_with_underscore invalid
  3. first_name valid
  4. last_name valid
  5. _illegal invalid

Use a negative look-ahead:

^(?!_)[a-zA-Z0-9_]+$

This is the same as the regex you had, except that ^(?!_) means the first character cannot be an underscore.

You can also just not include the _ in the first group

^[a-zA-Z0-9][a-zA-Z0-9_]*$

Or even:

^[^_][a-zA-Z0-9_]*$

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