简体   繁体   中英

how to run ruby syntax in a regex

ok so assume I have a variable that will be changing in every controller. @keyword and I am trying to find out if a specified keyword is in a post. My code is

= if posting.body =~ /<%= @keyword %>/
   then post //pseudocode here not my actual code. this isn't needed

I tried using .html_safe (I am using haml btw) and .raw(i wouldn't normally do this, but was suggested on another forum question that I didn't write. I only want to pass that instance variable from the controller. I don't think this would be hard, but I know there is a way.

= if posting.body =~ /#{@keyword}/

Try this and see if it works. I think this is how ruby is interpolated inside a regex.

The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

See here for the documentation.

If you are looking keyword in REGEX then your syntax will be:

posting.body =~ /^#{URI::regexp}$/

For variable:

posting.body =~ /^#{@keyword}$/

Try

= if posting.body =~ /#{@keyword}/
  then post

The <%= something %> in template is used to output some data to the response body. I believe that the code after = is just normal Ruby code.

BTW, you may need to escape the @keyword content, in case that it contains some special characters used in regular expression ( . for example).

= if posting.body =~ /#{Regexp.escape(@keyword)}/
  then post

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