RegEx for no whitespace at the beginning and end

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

    In cases when you have a specific pattern, say, ^[a-zA-Z0-9\s()-]+$, that you want to adjust so that spaces at the start and end were not allowed, you may use lookaheads anchored at the pattern start:

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

    Here,

    • (?!\s) - a negative lookahead that fails the match if (since it is after ^) immediately at the start of string there is a whitespace char
    • (?![\s\S]*\s$) - a negative lookahead that fails the match if, (since it is also executed after ^, the previous pattern is a lookaround that is not a consuming pattern) immediately at the start of string, there are any 0+ chars as many as possible ([\s\S]*, equal to [^]*) followed with a whitespace char at the end of string ($).

    In JS, you may use the following equivalent regex declarations:

    var regex = /^(?!\s)(?![\s\S]*\s$)[a-zA-Z0-9\s()-]+$/
    var regex = /^(?!\s)(?![^]*\s$)[a-zA-Z0-9\s()-]+$/
    var regex = new RegExp("^(?!\\s)(?![^]*\\s$)[a-zA-Z0-9\\s()-]+$")
    var regex = new RegExp(String.raw`^(?!\s)(?![^]*\s$)[a-zA-Z0-9\s()-]+$`)
    

    If you know there are no linebreaks, [\s\S] and [^] may be replaced with .:

    var regex = /^(?!\s)(?!.*\s$)[a-zA-Z0-9\s()-]+$/
    

    See the regex demo.

    JS demo:

    var strs = ['a  b c', ' a b b', 'a b c '];
    var regex = /^(?!\s)(?![\s\S]*\s$)[a-zA-Z0-9\s()-]+$/;
    for (var i=0; i<strs.length; i++){
      console.log('"',strs[i], '"=>', regex.test(strs[i]))
    }

    0 讨论(0)
  • 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.

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