RegEx for no whitespace at the beginning and end

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

    How about:

    ^\S.+\S$
    

    This will match any string that doesn't begin or end with any kind of space.

    0 讨论(0)
  • 2020-11-27 07:27

    pattern="^[^\s]+[-a-zA-Z\s]+([-a-zA-Z]+)*$" This will help you accept only characters and wont allow spaces at the start nor whitespaces.

    0 讨论(0)
  • 2020-11-27 07:28
    ^[^\s].+[^\s]$
    

    That's it!!!! it allows any string that contains any caracter (a part from \n) without whitespace at the beginning or end; in case you want \n in the middle there is an option s that you have to replace .+ by [.\n]+

    0 讨论(0)
  • 2020-11-27 07:29

    As a modification of @Aprillion's answer, I prefer:

    ^\S$|^\S[ \S]*\S$
    
    • It will not match a space at the beginning, end, or both.
    • It matches any number of spaces between a non-whitespace character at the beginning and end of a string.
    • It also matches only a single non-whitespace character (unlike many of the answers here).
    • It will not match any newline (\n), \r, \t, \f, nor \v in the string (unlike Aprillion's answer). I realize this isn't explicit to the question, but it's a useful distinction.
    0 讨论(0)
  • 2020-11-27 07:31

    This is the regex for no white space at the begining nor at the end but only one between. Also works without a 3 character limit :

    \^([^\s]*[A-Za-z0-9]\s{0,1})[^\s]*$\ - just remove {0,1} and add * in order to have limitless space between.

    0 讨论(0)
  • 2020-11-27 07:31
    ^[^0-9 ]{1}([a-zA-Z]+\s{1})+[a-zA-Z]+$
    

    -for No more than one whitespaces in between , No spaces in first and last.

    ^[^0-9 ]{1}([a-zA-Z ])+[a-zA-Z]+$
    

    -for more than one whitespaces in between , No spaces in first and last.

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