Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

后端 未结 8 2022
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 04:05

I\'m currently using this regex ^[A-Z0-9 _]*$ to accept letters, numbers, spaces and underscores. I need to modify it to require at least one number or letter s

8条回答
  •  一向
    一向 (楼主)
    2020-12-08 04:39

    You can use a lookaround:

    ^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$
    

    It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.

    UPDATE:

    Adding modifications suggested by Chris Lutz:

    ^(?=.*[^\W_])[\w ]*$/
    

提交回复
热议问题