RegEx for no whitespace at the beginning and end

后端 未结 14 1185
傲寒
傲寒 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', regex.test(strs[i]))
    }

提交回复
热议问题