Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Input + Ruby + Regex?

I want to give users a text area where they can enter text. Later I will match that input against a different input and extract it if matched.

Flow:

  • User enters text with returns into a text area
  • Text is saved in the db in a text field

Then I use the following to extract:

text_reply = text_reply.sub(/#{user.text_to_extract}/m, '').strip

Problem is that it appears that characters like new lines or pipes | are breaking it. As input that we want to match against can look like this:

XXXXXX

XXXXXX
XXXX & XXXXX
asdasd: 123312321 | dasasddsadasads

http://yahoo.com

Suggestions? Thansk

like image 310
AnApprentice Avatar asked Mar 22 '11 18:03

AnApprentice


People also ask

How do you accept user input in Ruby?

In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished. puts "My name is #{name}!"

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.

What is Rubular?

Rubular is a Ruby-based regular expression editor. It's a handy way to test regular expressions as you write them. To start, enter a regular expression and a test string.


1 Answers

You need to escape the input: http://www.ruby-doc.org/core/classes/Regexp.html

See the method escape.

 Regexp.escape(your_input)
like image 199
Michael Papile Avatar answered Nov 09 '22 11:11

Michael Papile