Reshma Suresh
Reshma Suresh

Reputation: 195

Why four backslashes in the regular expression?

"^\\\\d{1,2}$"

I have the above regex. I know that the string parser will remove two backlashes leaving us with \\d. Taking one for the meta-character, what is the function of the extraneous \ ? I haven't had previous experience in regex. Or is the string pattern is in itself [backslash][integer up to two occurences]. Am I missing something ?

Upvotes: 3

Views: 2638

Answers (2)

GolamMazid Sajib
GolamMazid Sajib

Reputation: 9447

There need to escape the \ so that your string literal can express it as data before you transform it into a regular expression.

First ^\\ means pattern start with \ and \\d{1,2} means digit(\d) should be occur 1 to 2 times. That's why there four back-slash.

Match case:

\12
\1
.......

Upvotes: 1

aghast
aghast

Reputation: 15310

Backslashes escape other backslashes, as well as special characters.

What you have there is:

  • \d is "digit", in your regex engine.
  • \\d is backslash-escaping-backslash + d, == \d, in your string quoting mechanism.
  • \\\\d is backslash-escaping-backslash, twice, +d, probably escaping the command line if you're using a shell, or if you have to pass the string through system or rsh or something.

Upvotes: 1

Related Questions