Reputation: 941
I want to create a RegExp in javascript. The requirement is to allow spaces at the beginning of a string if the string is non-empty. also, I have to restrict some special characters at the beginning of the string.
Currently, I am using this RegExp -
^(?!^[=+-@]).*
these strings need to be passed from regexp test -
foo
foo bar
bar
123bar
[email protected]
these string should fail -
@foo
@foo
' ...spaces'
'' empty-string
Please help.
Upvotes: 1
Views: 1420
Reputation: 626758
You can use
^(?! *[=+@-]| +$).*
Or, to match any kind of whitespaces:
^(?!\s*[=+@-]|\s+$).*
Details:
^
- start of string(?!\s*[=+@-]|\s+$)
- a negative lookahead that fails the match if, immediately to the right from the current location, there is
\s*[=+@-]
- zero or more whitespaces and then =
, +
, @
, or -
|
- or\s+$
- one or more whitespaces till end of string.*
- zero or more chars other than line break chars as many as possible.Upvotes: 2