kdonah3
kdonah3

Reputation: 155

Regex leading and trailing whitespace

I am looking for a regex expression that allows a-z, A-Z, any number, spaces, but it has to disallow whitespace at the END.

So far I have:

[a-zA-Z' ']+

I'm not sure how to allow any number and trim the whitespace at the end

Upvotes: 0

Views: 2920

Answers (3)

alpha bravo
alpha bravo

Reputation: 7948

how about this pattern using word boundary \b
\b[a-zA-Z0-9 ]+\b

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You could use a negative lookahead at the start.

^(?!.*\s$)[a-zA-Z\d ]+

(?!.*\s$) asserts that there isn't a space character exists at the end.

OR

^[a-zA-Z\d ]+(?<!\s)$

DEMO

Upvotes: 2

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

That's pretty simple:

^[a-zA-Z0-9 ]*[a-zA-Z0-9]$

I just special-cased the last character here. This required turning + into * for the remaining characters.

Upvotes: 3

Related Questions