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

后端 未结 8 1702
故里飘歌
故里飘歌 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:32

    This RegEx will allow neither white-space at the beginning nor at the end of. Your string/word and allows all the special characters.

    ^[^\s].+[^\s]$
    

    This Regex also works Fine

    ^[^\s]+(\s+[^\s]+)*$
    
    0 讨论(0)
  • 2020-12-16 15:34

    use \S at the beginning

    ^\S+[a-zA-Z0-9-_\\s]+$
    
    0 讨论(0)
  • 2020-12-16 15:35

    You need to use this regex:

    ^[^-\s][\w\s-]+$
    
    • Use start anchor ^
    • No need to double escape \s
    • Also important is to use hyphen as the first OR last character in the character class.
    • \w is same as [a-zA-Z0-9_]
    0 讨论(0)
  • 2020-12-16 15:36

    try this should work

    [a-zA-Z0-9_]+.*$
    
    0 讨论(0)
  • 2020-12-16 15:37

    /^[^.\s]/

    • try this instead it will not allow a user to enter character at first place
    • ^ matches position just before the first character of the string
    • . matches a single character. Does not matter what character it is, except newline
    • \s is space
    0 讨论(0)
  • 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-   "));

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