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?
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_]/.
=~ 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.
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.
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.
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]+/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With