Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Check if string/text includes a certain word/character via regex in controller

Tags:

I am working on a quoting mechanism in my app, where it should be possible to simply type #26, for example, in the comment form in order to quote comment 26 of that topic.
To check if a user wants to quote one or more comments in the first place, I put an if condition after my current_user.comments.build and before @comment.save.
But, just to make my question a bit more general and easier to adapt:

if @comment.content.include?(/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i) 

I want something like this. That example was for checking if the comment's content includes emails. But logically I get an "can't convert regexp to string" error.

How can you do the include? method in rails with an regexp? So, to check whether a text includes a string of a certain regex format?

Or is the controller the wrong place for such regex actions?

like image 978
rails_has_elegance Avatar asked Jun 09 '12 17:06

rails_has_elegance


People also ask

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Where do I find substrings in Ruby?

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.


1 Answers

I do ruby regex'es this way:

stringObj.match(/regex/) 
like image 121
Anna Billstrom Avatar answered Nov 09 '22 22:11

Anna Billstrom