Rails Regex warning: character class has a "-" without exit

I don't know much about regex soo. I just find some and try to use them.

Why do I have this error for this regex:

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

What is wrong here?

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

+6
source share
3 answers

A hyphen has special meaning in a regular expression, for example [az] means a character from z to.

If you want to match - , then it must be escaped or at the end (or start ) class.

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

OR

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

OR

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

Learn more Including a hyphen in a regex character bracket?

+10
source

Inside a character class, a hyphen is special . You can put a hyphen as the first or last character of a class. In some regex implementations, you can also place right after the range. If you place a hyphen somewhere else, you need to avoid it in order to add it to your class.

 [-a-zA-Z0-9._ ] 
+3
source

If you put - inside a character class, you need to avoid it because it has a special meaning (range) in the character class. Or you can put - at the beginning or at the end of the char class. If you do this like that, he won’t need to escape the character - inside the character class.

+2
source

Source: https://habr.com/ru/post/972509/


All Articles