Jean Tehhe
Jean Tehhe

Reputation: 1337

Ignore spaces at the end of a string

I use the following regex, which is working, but I want to add a condition so as to accept spaces at the end of the value. Currently it is not working.

What am I missinghere?

^[a-zA-Z][a-zA-Z0-9_]+\s?$[\s]*$

Upvotes: 0

Views: 87

Answers (3)

stema
stema

Reputation: 92976

Assumption: you added the two end of string anchors $ by mistake.

? quantifier, matching one or zero repetitions, makes the previous item optional

* quantifier, matching zero or more repetitions

So change your expression to

^[a-zA-Z][a-zA-Z0-9_]+\s*$

this is matching any amount of whitespace at the end of the string.

Be aware, whitespace is not just the space character, it is also tabs and newlines (and more)!

If you really want to match only space, just write a space or make a character class with all the characters you want to match.

^[a-zA-Z][a-zA-Z0-9_]+ *$

or

^[a-zA-Z][a-zA-Z0-9_]+[ \t]*$

Next thing is: Are you sure you only want plain ASCII letters? Today there is Unicode and you can use Unicode properties, scripts and blocks in your regular expressions.

Your expression in Unicode, allowing all letters and digits.

^\p{L}\w+\s*$

\p{L} Unicode property, any kind of letter from any language.

\w shorthand character class for word characters (letters, digits and connector characters like "_") [\p{L}\p{Nd}\p{Pc}] as character class with Unicode properties. Definition on msdn

Upvotes: 2

brainless coder
brainless coder

Reputation: 6430

Try this -

"^[a-zA-Z][a-zA-Z0-9_]+(\s)?$"

or this -

"^[a-zA-Z][a-zA-Z0-9_]+((\s){,})$"

$ indicates end of expression, if you are looking $ as character, then escape it with \

Upvotes: 1

aelor
aelor

Reputation: 11116

why two dollars?

^[a-zA-Z][a-zA-Z0-9_]+\s*$

or make it this :

"^[a-zA-Z][a-zA-Z0-9_]+\s?\$\s*$"

if you want to literally match the dollar.

Upvotes: 2

Related Questions