Reputation: 17622
I would like to have a regex which matches the string with NO whitespace(s) at the beginning. But the string containing whitespace(s) in the middle CAN match. So far i have tried below
[^-\s][a-zA-Z0-9-_\\s]+$
Above is not allowing whitespace(s) at the beginning, but also not allowing in the middle/end of the string. Please help me.
Upvotes: 25
Views: 90324
Reputation: 81
I suggest below regex for this,
^[^\s].*[^\s]$
You can try regex in here
Upvotes: 0
Reputation: 11
If your field for user name only accept letters and middle of space but not for begining and end
User name: /^[^\s][a-zA-Z\s]+[^\s]$/
If your field for user ID only accept letters,numbers and underscore and no spaces allow
user ID: /^[\w]+$/
If your field for password only accept letters,number and special character no spaces allow
Password: /^[\w@#&]+$/
Note: \w
content a-zA-Z
, number
, underscore (_
) if you add more character, add you special character after \w
.
You can compare with user ID and password field in password field im only add some special character (@#&
).
India public thoko like 😁
Upvotes: 1
Reputation: 627419
If you plan to match a string of any length (even an empty string) that matches your pattern and does not start with a whitespace, use (?!\s)
right after ^
:
/^(?!\s)[a-zA-Z0-9_\s-]*$/
^^^^^^
Or, bearing in mind that [A-Za-z0-9_]
in JS regex is equal to \w
:
/^(?!\s)[\w\s-]*$/
The (?!\s)
is a negative lookahead that matches a location in string that is not immediately followed with a whitespace (matched with the \s
pattern).
If you want to add more "forbidden" chars at the string start (it looks like you also disallow -
) keep using the [\s-]
character class in the lookahead:
/^(?![\s-])[\w\s-]*$/
To match at least 1 character, replace *
with +
:
/^(?![\s-])[\w\s-]+$/
See the regex demo. JS demo:
console.log(/^(?![\s-])[\w\s-]+$/.test("abc def 123 ___ -loc- "));
console.log(/^(?![\s-])[\w\s-]+$/.test(" abc def 123 ___ -loc- "));
Upvotes: 11
Reputation: 11
/^[^.\s]/
Upvotes: 1
Reputation: 569
This RegEx will allow neither white-space at the beginning nor at the end of. Your string/word and allows all the special characters.
^[^\s].+[^\s]$
This Regex also works Fine
^[^\s]+(\s+[^\s]+)*$
Upvotes: 5
Reputation: 786031
You need to use this regex:
^[^-\s][\w\s-]+$
^
\s
\w
is same as [a-zA-Z0-9_]
Upvotes: 7
Reputation: 213371
In your 2nd character class, \\s
will match \
and s
, and not \s
. Thus it doesn't matches a whitespace. You should use just \s
there. Also, move the hyphen towards the end, else it will create unintentional range in character class:
^[^-\s][a-zA-Z0-9_\s-]+$
Upvotes: 21