Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

regex - Why does sed require 3 backslashes for a regular backslash?

I'm curious, why does sed need 3 just to recognize one? I'd understand it needing 2, but 3 I don't.

EDIT: here's an example on my Windows computer, using Cygwin:

$ echo "sample_inputwhatever" | sed "s/\///"
sample_input/whatever

If I don't add 3 backslashes, I get a

sed: -e expression #1, char 7: unterminated s' command
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to reproduce this behavior using Vista and Cygwin 1.7.0.

  • Two backslashes produce the error
  • either three or four backslashes work
  • Five gives the same error

Two backslashes become a single backslash in the shell which then in sed escapes the forward slash which is the middle delimiter.

\/ -> / (which makes the forward slash a regular character instead of a delimiter)

Three of them: The first two become one in the shell which then escape the third one in sed

\/ -> \/

Four: Each pair become single ones in the shell then the first resulting one escapes the second in sed

\\/ -> \/ 

Edit:

Oh, I forgot to say that both single quotes and double quotes worked the same for me (cmd.exe doesn't make the distinction that Bash, et al, makes).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...