Javascript regex - no white space at beginning + allow space in the middle

后端 未结 8 1709
故里飘歌
故里飘歌 2020-12-16 15:15

I would like to have a regex which matches the string with NO whitespace(s) at the beginning. But the string containing whitespace(s) in the middle CAN match. So far i have

8条回答
  •  感情败类
    2020-12-16 15:45

    If you plan to match a string of any length (even an empty string) that matches your pattern and does not start with a whitespace, use (?!\s) right after ^:

    /^(?!\s)[a-zA-Z0-9_\s-]*$/
      ^^^^^^
    

    Or, bearing in mind that [A-Za-z0-9_] in JS regex is equal to \w:

    /^(?!\s)[\w\s-]*$/
    

    The (?!\s) is a negative lookahead that matches a location in string that is not immediately followed with a whitespace (matched with the \s pattern).

    If you want to add more "forbidden" chars at the string start (it looks like you also disallow -) keep using the [\s-] character class in the lookahead:

    /^(?![\s-])[\w\s-]*$/
    

    To match at least 1 character, replace * with +:

    /^(?![\s-])[\w\s-]+$/
    

    See the regex demo. JS demo:

    console.log(/^(?![\s-])[\w\s-]+$/.test("abc   def 123 ___ -loc-   "));
    console.log(/^(?![\s-])[\w\s-]+$/.test("  abc   def 123 ___ -loc-   "));

提交回复
热议问题