3

I need to make a regex pattern to check if whole input string is made out of characters a-z, A-Z, 0-9 without spaces in the middle. I tried using ^[ ]*[a-zA-Z0-9][ ]*$ to find but it doesn't work for some reason.

For example, " dnsjkfs32NJ" is a valid string but "fds fsdfs" is not.

Thanks. :)

1
  • Where are you using this regex? Perl? PHP? Ruby? grep? C#? Dec 28, 2012 at 19:11

1 Answer 1

5

This might work for you

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

You're missing a + after your character class; without it, it's matching one and only one character.

2
  • \s is any whitespace: space, tab, etc.
    – Barmar
    Dec 28, 2012 at 19:16
  • personally, I'd use a trim function, instead of whitespace matching. Personal preference, but I find I often need to trim the string anyway. Dec 28, 2012 at 21:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.