views:

120

answers:

3

I'm a newbie to RegEx, and this particular issue is flummoxing me. This is for use with a JavaScript function.

I need to validate an input so that it matches only this criteria:

  • Letters A-Z (upper and lowercase)
  • Numbers 0-9
  • The following additional characters: space, period (.), comma (,), plus (+), and dash (-)

I can write a pattern easily enough for the first two criteria, but the third one is more difficult. This is the last pattern I managed, but it doesn't seem to work with the test string Farh%%$$+++,

Any help would be greatly appreciated.

Thank you.

+2  A: 

The dash needs to be first in order not to be interpreted as a range separator. Also, make sure you anchor your regex with a ^ and $ at the beginning and end respectively so that your entire test string gets swallowed by your regex.

/^[-+., A-Za-z0-9]+$/
Asaph
within the character classes dot and plus are literal characters.
SilentGhost
@SilentGhost: fixed. Thanks.
Asaph
az- should be a-z
Grandpa
doesn't seem to be fixed
SilentGhost
@Grandpa: I fixed a-z. Thanks. Geez, hurrying makes for sloppy typing...
Asaph
@SilentGhost: removed slashes from period and plus
Asaph
The dash can also appear at the end or between character ranges in order not to be interpreted as a range separator: `[a-z0-9-]` and `[a-z-0-9]` are valid expressions too.
Gumbo
+2  A: 
/^[a-z0-9 .,+-]+$/i
SilentGhost
+1  A: 

I just tested this out, and it seems to work at least from my first round testing.

^[a-zA-Z 0-9\.\,\+\-]*$
Mitchel Sellers
except that it matches an empty string (and tab charatecter) and you don't need to escape any of those characters
SilentGhost
@SlientGhost Good point on the empty string, but technically anything that allows a space, and using a single character class will allow all spaces. As for the escaping, I was just being careful, I was running this through a .NET RegEx tester and seeing funny results.
Mitchel Sellers
I think this might do it. Had to add 0-9 to make it match numbers.
RHPT
you see, it's not just tabs, in Javascript `\s` matches spaces, tabs, line breaks plus *any* Unicode whitespace characters, which, it seems to me, is slightly more than what OP wanted.
SilentGhost
Ah yes, forgot the 0-9, and removed the \s
Mitchel Sellers