MattB
MattB

Reputation: 31

how to unescape \\ in a regex that has been escaped by Rails?

I'm trying to store regexes in a database but they're getting escaped by rails.

For example \w*\s\/\s becomes \\w*\\s\\/\\s in the database and when retrieved.

I'm inserting trying to use them with mystring.sub(/#{regex_variable}/, ''), but the escaped regex is not matching as desired.

What's the best we to resolve this so the regex works as input?

Thanks!

Upvotes: 2

Views: 1071

Answers (3)

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38586

I think what Crayon means in Ruby is:

mystring.gsub("\\\\", "\\")

I think I escaped them correctly.

Sorry if I misunderstood the question.

EDIT: For that question, refer to this question.

Upvotes: 1

MattB
MattB

Reputation: 31

Thanks for the suggestions. As it turns out the Rails console escapes the backslashes on output (why?). That also explains why when I'd tried the gsub that Blaenk suggested, it didn't appear to be working (I had previously tried that myslef to no avail).

So my question now is why the regex works when I put it directly i quotes, but not in mystring.sub(/#{regex_variable}/, '') form, but I guess I need to open a new quoestion for that.

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32532

I don't know ruby syntax but you could do a global replace of \\ for \

Upvotes: 0

Related Questions