Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Regex warning: character class has '-' without escape

I'm doesn't know much about regex soo I just find some and try to use it.

Why I have this error for this regex:

warning: character class has '-' without escape: /[a-zA-Z0-9-._ ]/

What is wrong here?

validations shoud have only letters, numbers and "-" , "." , "_", " " (blank space)

like image 517
Wordica Avatar asked Jul 19 '14 17:07

Wordica


2 Answers

hyphen has special meaning in regex for example [a-z] means a to z character.

If you want to match - then it should either be escaped or be at the end (or start) of the class.

[a-zA-Z0-9._ -]

OR

[-a-zA-Z0-9._ ]

OR

[a-zA-Z0-9\-._ ]

Read more Including a hyphen in a regex character bracket?

like image 113
Braj Avatar answered Oct 02 '22 21:10

Braj


Inside of a character class the hyphen has special meaning. You can place a hyphen as the first or last character of the class. In some regular expression implementations, you can also place directly after a range. If you place the hyphen anywhere else you need to escape it in order to add it to your class.

[-a-zA-Z0-9._ ]
like image 39
hwnd Avatar answered Oct 02 '22 21:10

hwnd