javascript regex to allow at least one special character and one numeric

前端 未结 3 2039
天命终不由人
天命终不由人 2021-01-24 04:43

Im beginer about regex...I need to create a regular expression to check if a string has got at least one special character and one numeric. Im using ([0-9]+[!@#$%\\^&*

3条回答
  •  一向
    一向 (楼主)
    2021-01-24 05:01

    If, by special characters, you mean all ASCII printable symbols and punctuation that can be matched with [!-\/:-@[-`{-~] pattern (see Check for special characters in string, you may find more special character patterns there), you may use

    /^(?=.*?\d)(?=.*?[!-\/:-@[-`{-~])/
    

    Or, taking into account the contrast principle:

    /^(?=\D*\d)(?=[^!-\/:-@[-`{-~]*[!-\/:-@[-`{-~])/
    

    See the regex demo (I added .* at the end and \n to the negated character classes in the demo because the regex is tested against a single multiline string there, you do not need them in the regex testing method in the code).

    Details

    • ^ - start of string
    • (?=.*?\d) - there must be at least one digit after any 0 or more characters other than line break chars, as few as possible
    • (?=\D*\d) - there must be at least one digit after any 0 or more characters other than a digit
    • (?=.*?[!-\/:-@[-{-~])` - there must be at least one printable ASCII punctuation/symbol after any 0 or more characters other than line break chars, as few as possible
    • (?=[^!-\/:-@[-{-~]*[!-/:-@[-{-~]) - there must be at least one printable ASCII punctuation/symbol after any 0 or more characters other than a printable ASCII punctuation/symbol.

提交回复
热议问题