admin管理员组

文章数量:1231080

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.

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.

Share Improve this question asked Sep 11, 2009 at 20:31 Kyle HayesKyle Hayes 5,2928 gold badges40 silver badges53 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 36

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]/) 
if(someString.match(/[a-z -]+/i){
    // it's valid
}

本文标签: JavaScript Regex (string should include only alphaSpacehyphen)Stack Overflow