14

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)

Wordica
  • 2,427
  • 3
  • 31
  • 51

3 Answers3

25

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?

Braj
  • 46,415
  • 5
  • 60
  • 76
4

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._ ]
hwnd
  • 69,796
  • 4
  • 95
  • 132
3

If you put - inside a character class, you need to escape it because it has a special meaning(range) in character class. Or you could put the - at the start or at the end of char class. If you do like this, it won't need escaping of - symbol inside character class.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274