Preventing spaces with RegEx

I am trying to restrict the viewing of text posting to text (currently) by the following RegEx:

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

However, the text itself must contain spaces in the form, '' but I do not want the first sentence to have spaces, i.e. a column cannot have leading spaces. For example, (I will use '_' to represent '' in the following example), the form would allow:

This is a sentence.

But this did NOT allow:

(Using '_' to represent '')

_This is a sentence

__This is a sentence

and etc.

I tried to work with negatives, but I just don't understand RegEx well enough to figure out how to do this. All this field is not sitting very well with me, so I hope 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 to understand this in real time will be sufficient for my purposes, if you think about something better.

+4
source share
3 answers

You can also use negative browsing :

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

If you want to allow these characters the restriction that the first should not be a space, you need to repeat the group of characters:

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

Or you do two tests:

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

Just use ^ \ S at the beginning of your regular expression, where ā€œ^ā€ is the beginning of the line and ā€œ\ Sā€ is the negation of the space character class.

0
source

All Articles