Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to escape dash character in regex? [duplicate]

I'm trying to understand dash character - needs to escape using backslash in regex?

Consider this:

var url     = '/user/1234-username'; var pattern = /\/(\d+)\-/; var match   = pattern.exec(url); var id      = match[1]; // 1234  

As you see in the above regex, I'm trying to extract the number of id from the url. Also I escaped - character in my regex using backslash \. But when I remove that backslash, still all fine ....! In other word, both of these are fine:

  • /\/(\d+)\-/
  • /\/(\d+)-/

Now I want to know, which one is correct (standard)? Do I need to escape dash character in regex?

like image 626
Shafizadeh Avatar asked Feb 21 '16 13:02

Shafizadeh


People also ask

Which characters should be escaped in regex?

Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.

Do we need to escape Colon in regex?

Colon does not have special meaning in a character class and does not need to be escaped.

Is Dash a special character?

The hyphen is mostly a normal character in regular expressions. You do not need to escape the hyphen outside of a character class; it has no special meaning.


2 Answers

You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).

/-/        # matches "-" /[a-z]/    # matches any letter in the range between ASCII a and ASCII z /[a\-z]/   # matches "a", "-" or "z" /[a-]/     # matches "a" or "-" /[-z]/     # matches "-" or "z" 
like image 118
Tim Pietzcker Avatar answered Oct 04 '22 08:10

Tim Pietzcker


- has a meaning only inside a character class [], so when you're outside of it you don't need to escape -

like image 34
Gavriel Avatar answered Oct 04 '22 10:10

Gavriel