Michael Kuan
Michael Kuan

Reputation: 1101

Regular expression - not allow space at the beginning

Refer to my regular expression:

^(?!.*  )[^#+&\'\"\\\\]*$

I want to restrcit user to enter space at the beginning , for example:
(space)123 ---> invalid

How should I add it into the above regular expression?
Can someone help me?

Upvotes: 1

Views: 657

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

You may add an alternative to the lookahead:

^(?! |.*  )[^#+&\'\"\\\\]*$
 ^^^^^^^^^^

See the regex demo

The (?! |.* ) negative lookahead fails the match if a space appears right at the start of the string, or if there are double consecutive spaces somewhere after any 0+ chars (depending on the DOTALL option or regex flavor, any chars other than line break chars).

The same pattern can be written in a more linear way, as

^(?!(?:.* )? )[^#+&\'\"\\\\]*$

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

to restrcit user to enter space at the beginning

Even simpler using character class [^\s]+? which allows only non-space characters at the start of the string:

^[^\s]+?[^#+&\'\"\\\\]*$

Upvotes: 1

Related Questions