I’m trying to build a regex from a string object, which happens to be stored in a variable.
The problem I’m facing is that escaped sequences (in the string) such “\d” doesn’t make to the resulting regex.
Regexp.new("\d") => /d/
If I use single quotes, tough, it works flawless.
Regexp.new('\d') => /\d/
But, as my string is stored in a variable, I always get the double-quoted string.
Is there a way to turn a double-quoted string to single-quoted string, so that I could use in the Regexp constructor ?
(I’d like to use the string interpolation feature of the double quotes)
ex.:
email_pattern = "/[a-z]*\.com"
whole_pattern = "to: #{email_pattern}"
Regexp.new(whole_pattern)
For better readability, I’d like to avoid escaping escape characters.
"\\d"
The problem is, that you end up with completely different strings, depending on whether you use single or double quotes:
so when you are using double quotes, the single
\is immediately lost and cannot be recovered by definition, for example:so you can never know what the string contained before the escaping took place. As @FrankSchmitt suggested, use the double backslash or stick with single quotes. There’s no other way.
There’s an option, though. You can define your regex parts as regexes themselves, instead of strings. They behave exactly as expected:
Then, you can build your final regex with
#{}-style interpolation, instead of building the regex source from strings:Reflecting your example this would translate to:
You may also find
Regexp#escapeinteresting. (see the docs)If you run into further escaping problems (with the slashes), you can also use the alternative Regexp literal syntax with
%r{<your regex here>}, in which you do not need to escape the/character. For example:There’s no getting around escaping the backslash
\with\\, though.