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

后端 未结 8 1985
隐瞒了意图╮
隐瞒了意图╮ 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:28

    This will validate against special characters and leading and trailing spaces:

    var strString = "Your String";
    
    strString.match(/^[A-Za-z0-9][A-Za-z0-9 ]\*[A-Za-z0-9]\*$/)
    
    0 讨论(0)
  • 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 ]*$/
    
    0 讨论(0)
提交回复
热议问题