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
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.
This worked for me:
^[^\s].+[a-zA-Z]+[a-zA-Z]+$
Hope it helps.
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.
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/
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
Letters and numbers divided only by one space. Also, no spaces allowed at beginning and end.
/^[a-z0-9]+( [a-z0-9]+)*$/gi