RegEx for no whitespace at the beginning and end

后端 未结 14 1154
傲寒
傲寒 2020-11-27 07:20

I want to design an expression for not allowing whitespace at the beginning and at the end of a string, but allowing in the middle of the string.

The regex I\'ve tri

14条回答
  •  暖寄归人
    2020-11-27 07:31

    Other answers introduce a limit on the length of the match. This can be avoided using Negative lookaheads and lookbehinds:

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

    This starts by checking that the first character is not whitespace ^(?!\s). It then captures the characters you want a-zA-Z0-9\s non greedily (*?), and ends by checking that the character before $ (end of string/line) is not \s.

    Check that lookaheads/lookbehinds are supported in your platform/browser.

提交回复
热议问题