Regex pattern to match at least 1 number and 1 character in a string

后端 未结 9 2457
既然无缘
既然无缘 2020-11-22 13:22

I have a regex

/^([a-zA-Z0-9]+)$/

this just allows only alphanumerics but also if I insert only number(s) or only

相关标签:
9条回答
  • 2020-11-22 13:59

    Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:

    /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/
    
    0 讨论(0)
  • 2020-11-22 14:00

    If you need the digit to be at the end of any word, this worked for me:

    /\b([a-zA-Z]+[0-9]+)\b/g
    
    • \b word boundary
    • [a-zA-Z] any letter
    • [0-9] any number
    • "+" unlimited search (show all results)
    0 讨论(0)
  • 2020-11-22 14:06

    And an idea with a negative check.

    /^(?!\d*$|[a-z]*$)[a-z\d]+$/i
    
    • ^(?! at start look ahead if string does not
    • \d*$ contain only digits | or
    • [a-z]*$ contain only letters
    • [a-z\d]+$ matches one or more letters or digits until $ end.

    Have a look at this regex101 demo

    (the i flag turns on caseless matching: a-z matches a-zA-Z)

    0 讨论(0)
提交回复
热议问题