RegEx for no whitespace at the beginning and end

后端 未结 14 1179
傲寒
傲寒 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:45

    This RegEx will allow neither white-space at the beginning nor at the end of your string/word.

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

    Any string that doesn't begin or end with a white-space will be matched.

    Explanation:

    1. ^ denotes the beginning of the string.
    2. \s denotes white-spaces and so [^\s] denotes NOT white-space. You could alternatively use \S to denote the same.
    3. . denotes any character expect line break.
    4. + is a quantifier which denote - one or more times. That means, the character which + follows can be repeated on or more times.

    You can use this as RegEx cheat sheet.

提交回复
热议问题