Matt
Matt

Reputation: 1570

Prevent Leading Whitespace with RegEx

I'm trying to restrict review posting text with (at the present) the following RegEx:

^([a-zA-Z0-9 _\.\'\"\(\)\!\?\&\@]){1,}$

However, the text itself needs to contain whitespace in the form of ' ', but I don't want to allow the first sentence to have whitespace, i.e. the post cannot have leading whitespace. For an example, (I'm going to use '_' to represent ' ' in the following example) the form would allow:

This is a sentence.

But it would NOT allow:

(Using '_' to represent ' ')

_This is a sentence

__This is a sentence

etc.

I tried to work with negations, but I just don't understand RegEx well enough to grasp how to do this. This whole field is just not sitting well with me, so hopefully someone can help. Thanks in advance!

NOTE: I need this in RegEx because I have a live-feed validator telling the user that his/her input is valid/invalid. Another option that will allow me this real-time awareness will be sufficient for my purposes, if you happen to think of something better.

Upvotes: 4

Views: 9036

Answers (3)

Jayendra
Jayendra

Reputation: 52779

You can also use a negative lookahead:

^(?!\s)([a-zA-Z0-9 _.'"()!?&@]){1,}$

Upvotes: 12

Red Orca
Red Orca

Reputation: 4785

Just use ^\S at the beginning of your regex, where the '^' is the beginning of the string, and '\S' is the negation of the whitespace character class.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816422

If you only want to allow these characters with the restriction that the first one should not be a whitespace, you have to repeat the character group:

/^[a-zA-Z0-9 _.'"()!?&@][a-zA-Z0-9 _.'"()!?&@\s]+$/

Or you make two tests:

if(!/^\s/.test(str) && /^[a-zA-Z0-9 _.'"()!?&@]+$/.test(str)) {
    // valid
}

Upvotes: 1

Related Questions