Why does Regexp::escape backslash spaces?!?

  • Thread starter Marnen Laibow-Koser
  • Start date
M

Marnen Laibow-Koser

$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]
$ irb
irb(main):001:0> Regexp::escape('a b')
=> "a\\ b"

Why? This doesn't seem to make any sense. Is it a bug?

Best,
 
K

Kirk Haines

$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]
$ irb
irb(main):001:0> Regexp::escape('a b')
=3D> "a\\ b"

Why? =A0This doesn't seem to make any sense. =A0Is it a bug?

It is intentional. In re.c:rb_reg_quote()

switch (c) {
case '[': case ']': case '{': case '}':
case '(': case ')': case '|': case '-':
case '*': case '.': case '\\':
case '?': case '+': case '^': case '$':
case ' ': case '#':
case '\t': case '\f': case '\n': case '\r':
goto meta_found;
}


And then down in meta_found:

case ' ':
*t++ =3D '\\';
*t++ =3D ' ';
continue;


Kirk Haines
 
A

Albert Schlef

Marnen said:
irb(main):001:0> Regexp::escape('a b')
=> "a\\ b"

Why? This doesn't seem to make any sense. Is it a bug?


Maybe spaces are escaped so the resulting string be compatible with an
"extended" pattern, where non-escaped spaces are ignored:

/ (\w+) \s (\w+) /x

is the same as:

/(\w+)\s(\w+)/
 
M

Marnen Laibow-Koser

Albert said:
Maybe spaces are escaped so the resulting string be compatible with an
"extended" pattern, where non-escaped spaces are ignored:

/ (\w+) \s (\w+) /x

is the same as:

/(\w+)\s(\w+)/

Good point. And anyway, it causes no problems: when I first posted, I
thought it did, but those problems actually came from elsewhere.

Best,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top