简体   繁体   中英

Ruby: Rubeque: Variable in regexp?

I'm solving http://www.rubeque.com/problems/a-man-comma--a-plan-comma--a-canal--panama-excl-/solutions but I'm a bit confused about treating #{} as comment in regexp. My code look like this now

def longest_palindrome(txt)
  txt[/#{txt.reverse}/]
end

I tried txt[/"#{txt.reverse}"/] or txt[#{txt.reverse}] but nothing works as I wish. How should I implicate variable into regexp?

This is not something you can do with a regex.

While you could use variable interpolation in the construction of a regex (see the other answers/comments), that wouldn't help you here. You could only use that to reverse a literal string, not a regex match result. Even if you could, you still wouldn't have solved the "find the longest palindrome" part, at least not with acceptable runtime performance.

Use a different approach to the problem.

It is hard to tell how do you wish that happens without examples, but I suppose you are after

txt[/#{Regexp.escape(txt.reverse)}/]

See the Regexp#escape method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM