简体   繁体   中英

Regular expression to only allow letters and space in input filed but the first character should not be space

New to regex. I am validating a input filed. I need to write regular expression which checks the following: Only letters and spaces are allowed not numbers and special charactes The first character should be a valid letter [a-zA-Z] not a space. Thank you

The following regex accepts only letters or spaces as you wanted.

^(?! )[A-Za-z\s]*$

Quick explanation:

^ Matches beginning of input

(?! ) Zero-width negative look-ahead assertion aka "not followed by...", so the first letter won't be a space character

[A-Za-z\\s]* Accept only letters (A-Za-z) and spaces (\\s) any time (*)

$ Matches end of input

Edit : If you don't want to match an empty string, then need to accept at least one character instead of any : ^(?! )[A-Za-z\\s]+$

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