2

I need to convert back and forth between the string representation of a Regexp and the Regexp itself.

Something like this:
> Regexp.new "\bword\b|other
=> /\bword\b|other/

However, doing so results in /\x08word\x08|other/

Is there some way to accomplish this?

4
  • What are you expecting \b to match in the regex? Commented Apr 9, 2018 at 19:58
  • I'd like \b to match a word boundary. e.g. "sword" would not match /\bword\b/ but "word" would. Commented Apr 9, 2018 at 20:00
  • You need to escape the backslashes so they are treated as characters, as opposed to escaping the following character: Regexp.new "\\bword\\b|other" #=> /\bword\b|other/. Commented Apr 9, 2018 at 20:10
  • It's probably easier to start with a regex and use to_s / source to get its string representation. Commented Apr 10, 2018 at 7:13

1 Answer 1

2

Use single quotes, or escape the backslashes.

p re = Regexp.new('\bword\b|other') # => /\bword\b|other/
p re = Regexp.new("\\bword\\b|other")  # => /\bword\b|other/

p re.to_s  # => "(?-mix:\\bword\\b|other)"
p re.inspect # => "/\\bword\\b|other/"

The resulting string of to_s can be used as argument for Regexp.new (as can the regular expression itself).

Sign up to request clarification or add additional context in comments.

1 Comment

Also worth mentioning %r(#{str}) for interpolated regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.