rr87
rr87

Reputation: 185

Regex to allow special characters

I need a regex that will allow alphabets, hyphen (-), quote ('), dot (.), comma(,) and space. this is what i have now

^[A-Za-z\s\-]$ 

Thanks

Upvotes: 1

Views: 5984

Answers (3)

Bergi
Bergi

Reputation: 664277

You probably tried new RegExp("^[A-Za-z\s\-\.\'\"\,]$"). Yet, you have a string literal there, and the backslashes just escape the following characters - necessary only for the delimiting quote (and for backslashes).

"^[A-Za-z\s\-\.\'\"\,]$" === "^[A-Za-zs-.'\",]$" === '^[A-Za-zs-.\'",]$'

Yet, the range s-. is invalid. So you would need to escape the backslash to pass a string with a backslash in the RegExp constructor:

new RegExp("^[A-Za-z\\s\\-\\.\\'\\\"\\,]$")

Instead, regex literals are easier to read and write as you do not need to string-escape regex escape characters. Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated. The RegExp constructor only needs to be used if you want to build regexes dynamically. So use

/^[A-Za-z\s\-\.\'\"\,]$/

and it will work. Also, you don't need to escape any of these chars in a character class - so it's just

/^[A-Za-z\s\-.'",]$/

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208405

You are pretty close, try the following:

^[A-Za-z\s\-'.,]+$

Note that I assumed that you want to match strings that contain one or more of any of these characters, so I added + after the character class which mean "repeat the previous element one or more times".

Note that this will currently also allow tabs and line breaks in addition to spaces because \s will match any whitespace character. If you only want to allow spaces, change it to ^[A-Za-z \-'.,]+$ (just replaced \s with a space).

Upvotes: 0

Daniel Gimenez
Daniel Gimenez

Reputation: 20494

I removed \s from your regex since you said space, and not white space. Feel free to put it back by replacing the space at the end with \s Otherwise pretty simple:

 ^[A-Za-z\-'., ]+$

It matches start of the string. Any character in the set 1 or more times, and end of the string. You don't have to escape . in a set, in case you were wondering.

Upvotes: 1

Related Questions