I'm trying to create a regex that will match only when the string has anything but alphas, spaces, and hyphens. In other words, the string can only contain letters, spaces, and hyphens.
"the string can only contain letters, spaces, and hyphens."
inkedmn
2009-09-11 20:35:57
change regexp to this: /[^a-z \-]+/i
Eimantas
2009-09-11 20:36:34
Eimantas - there's no need to change the regex
inkedmn
2009-09-11 20:38:41
If you don't anchor your expression with ^ and $, this will simply match a substring. The rest of the string can still contain unwanted characters.
Ates Goral
2009-09-11 20:39:13
Ah, yes, you're right. Silly me :)
inkedmn
2009-09-11 20:43:11
It works - its basically the same as the second part of my answer. It tests the failure case.
gnarf
2009-09-12 02:25:35
Ok, which is correct. I need it to test the failure case. Sorry if I wasn't clear about that.
Kyle Hayes
2009-09-13 14:14:36
+5
A:
If you are looking for a test for validity:
// from string start to end, only contains '-' "whitespace" or 'a'-'z'
someString.match(/^[-\sa-zA-Z]+$/)
Or the negation:
// has some invalid character not '-' "whitespace" or 'a'-'z'
someString.match(/[^-\sa-zA-Z]/)
gnarf
2009-09-11 20:40:32