Question

I only want to allow a-z, A-Z and space in between characters. For this I am using following regex, problem is that it allows the leading and trailing spaces also. Can this be adjusted to not allow leading or trailing white space.

[a-zA-Z\\ \\\']*

examples 'prince charles' should pass
' prince charles' should fail due to leading whitespace
'prince charles ' should fail due to trailing whitespace

Was it helpful?

Solution

To dis-allow leading and trailing whitespace, you can use:

^[a-zA-Z](?:[a-zA-Z ]*[a-zA-Z])?$

OTHER TIPS

Word boundaries. It's as simple as that:

^\b[a-zA-Z ]*\b$
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top