Javascript RegEx partial match

后端 未结 6 1881
轮回少年
轮回少年 2021-01-04 03:20

I have a regular expression pattern, which validates for a three digit number

/^\\d{3}$/.test(\"123\")   // true
/^\\d{3}$/.test(\"123.\")  // false
<         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 03:59

    You'll want to use explicit "|" partial matches. For your color matching example it's pretty simple, you just need to explicitly match an empty string partial

    /^(|#[a-f0-9]{0,6})$/i.test(inputStr)
    

    For an email it's more complicated since there are more partial match combinations

    /^(|\w+|\w+@|\w+@\w+|\w+@\w+\.|\w+@\w+\.\w+)$/.test(inputStr)
    

    Note that you can't get away with something like /^(|\w*@|...)$/ since that matches @blah.com which isn't a valid partial input.

提交回复
热议问题