RegEx for no whitespace at the beginning and end
Asked Answered
C

19

30

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 tried is this:

\^[^\s][a-z\sA-Z\s0-9\s-()][^\s$]\
Chequer answered 24/1, 2016 at 11:1 Comment(2)
How is angular relevant? What kind of regexp? For JavaScript, as defined in ECMA-262? Do you use a regex literal in your js code? Why don't you just describe the language in words. something like this: "the set of words that do not start or end with whitespace." But what about the empty word?Northing
the regular expression will be hard to read and understand. This expression would be much simpler: str.trim() === strNorthing
A
52

This should work:

^[^\s]+(\s+[^\s]+)*$

If you want to include character restrictions:

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

Explanation:

the starting ^ and ending $ denotes the string.

considering the first regex I gave, [^\s]+ means at least one not whitespace and \s+ means at least one white space. Note also that parentheses () groups together the second and third fragments and * at the end means zero or more of this group. So, if you take a look, the expression is: begins with at least one non whitespace and ends with any number of groups of at least one whitespace followed by at least one non whitespace.

For example if the input is 'A' then it matches, because it matches with the begins with at least one non whitespace condition. The input 'AA' matches for the same reason. The input 'A A' matches also because the first A matches for the at least one not whitespace condition, then the ' A' matches for the any number of groups of at least one whitespace followed by at least one non whitespace.

' A' does not match because the begins with at least one non whitespace condition is not satisfied. 'A ' does not matches because the ends with any number of groups of at least one whitespace followed by at least one non whitespace condition is not satisfied.

If you want to restrict which characters to accept at the beginning and end, see the second regex. I have allowed a-z, A-Z, 0-9 and () at beginning and end. Only these are allowed.

Regex playground: http://www.regexr.com/

Annulus answered 24/1, 2016 at 11:5 Comment(0)
T
10

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.

Turtleneck answered 24/1, 2016 at 12:20 Comment(1)
How can we make it work without 3 character limit? So even if user enters one character it should pass validationPhilip
M
9

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]))
}
Metalinguistics answered 20/3, 2020 at 22:50 Comment(0)
I
7

if the string must be at least 1 character long, if newlines are allowed in the middle together with any other characters and the first+last character can really be anyhing except whitespace (including @#$!...), then you are looking for:

^\S$|^\S[\s\S]*\S$

explanation and unit tests: https://regex101.com/r/uT8zU0

Ics answered 24/1, 2016 at 12:33 Comment(0)
J
5

This worked for me:

^[^\s].+[a-zA-Z]+[a-zA-Z]+$

Hope it helps.

Jaws answered 28/11, 2019 at 11:57 Comment(1)
I look for something similar but to apply for multi language web forms. The unicode topic is important. I read that with Javascript is no so effective, but it is with PCRE. I have this code: /[^\s]([\p{L}\-' ][^\s]){1,30}/ I included a hyphen, an apostrophe because they are included in some english names, but might not be necessary, I am not sure, are they part of \p{M} ?Brie
Z
2

How about:

^\S.+\S$

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

Zephan answered 24/1, 2016 at 11:55 Comment(2)
. will match \n or not based on the multiline flag and the string will have to be at least 3 characters long...Ics
Not work if there be just 1 character.Karlynkarma
K
2

If we do not have to make a specific class of valid character set (Going to accept any language character), and we just going to prevent spaces from Start & End, The must simple can be this pattern:

/^(?! ).*[^ ]$/

Try on HTML Input:

input:invalid {box-shadow:0 0 0 4px red}
/* Note: ^ and $ removed from pattern. Because HTML Input already use the pattern from First to End by itself. */
<input pattern="(?! ).*[^ ]">

Explaination

  • ^ Start of
  • (?!...) (Negative lookahead) Not equal to ... > for next set
  • Just Space / \s (Space & Tabs & Next line chars)
    • (?! ) Do not accept any space in first of next set (.*)
  • . Any character (Execpt \n\r linebreaks)
  • * Zero or more (Length of the set)
  • [^ ] Set/Class of Any character expect space
  • $ End of

Try it live: https://regexr.com/6e1o4

Karlynkarma answered 26/1, 2022 at 0:12 Comment(0)
R
1
^[^\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]+

Retinol answered 24/1, 2016 at 12:25 Comment(1)
it need two char to matchPriapic
B
1

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.

Burnedout answered 4/12, 2017 at 12:57 Comment(0)
N
1

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.

Niven answered 4/6, 2019 at 22:11 Comment(1)
At the moment I can add only 2 words. How can I remove this limitation and to be able to enter how many words I want ?Nippur
O
1

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.
Ostrowski answered 17/8, 2019 at 17:35 Comment(0)
P
1

Letters and numbers divided only by one space. Also, no spaces allowed at beginning and end.

/^[a-z0-9]+( [a-z0-9]+)*$/gi
Petrography answered 26/11, 2019 at 19:55 Comment(0)
R
1

I found a reliable way to do this is just to specify what you do want to allow for the first character and check the other characters as normal e.g. in JavaScript:

RegExp("^[a-zA-Z][a-zA-Z- ]*$")

So that expression accepts only a single letter at the start, and then any number of letters, hyphens or spaces thereafter.

Roller answered 3/11, 2020 at 0:3 Comment(0)
E
0
^[^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.

Entrench answered 25/2, 2019 at 7:30 Comment(0)
P
0

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])*?(?<!\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.

Patterson answered 18/11, 2019 at 20:46 Comment(1)
I am using the reactive form, that pattern helps me to solve this issue "^(?!\\s)(?![^]*\\s$)[a-zA-Z0-9\\s()-]+$"Overtrick
D
0

use /^[^\s].([A-Za-z]+\s)*[A-Za-z]+$/. this one. it only accept one space between words and no more space at beginning and end

Duisburg answered 18/2, 2021 at 10:0 Comment(0)
L
0

Here you go,

\b^[^\s][a-zA-Z0-9]*\s+[a-zA-Z0-9]*\b

  • \b refers to word boundary
  • \s+ means allowing white-space one or more at the middle.
Langan answered 9/7, 2021 at 13:27 Comment(0)
S
0
(^(\s)+|(\s)+$)

This expression will match the first and last spaces of the article..

Spector answered 22/9, 2021 at 5:22 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Cordwood
O
0

^([^\s].+[^\s])$|^\S{1,2}$

To allow at least one character, but no white space at end and beginning.

Oxcart answered 14/12, 2023 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.