Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to regular expression ruby

I need to convert string like "/[\w\s]+/" to regular expression.

"/[\w\s]+/" => /[\w\s]+/ 

I tried using different Regexp methods like:

Regexp.new("/[\w\s]+/") => /\/[w ]+\//, similarly Regexp.compile and Regexp.escape. But none of them returns as I expected.

Further more I tried removing backslashes:

Regexp.new("[\w\s]+") => /[w ]+/ But not have a luck.

Then I tried to do it simple:

str = "[\w\s]+" => "[w ]+" 

It escapes. Now how could string remains as it is and convert to a regexp object?

like image 626
cmthakur Avatar asked Dec 28 '11 06:12

cmthakur


People also ask

How do you write regular expressions in Ruby?

Matches a whitespace character: /[ \t\r\n\f]/. Matches non-whitespace: /[^ \t\r\n\f]/. Matches a single word character: /[A-Za-z0-9_]/. Matches a non-word character: /[^A-Za-z0-9_]/.

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

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

Looks like here you need the initial string to be in single quotes (refer this page)

>> str = '[\w\s]+'  => "[\\w\\s]+"  >> Regexp.new str  => /[\w\s]+/  
like image 100
alony Avatar answered Oct 05 '22 06:10

alony