Convert a String to Regular Expression Ruby

Convert a string to regular expression ruby

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]+/

Convert a regular expression in a string to a regexp object in ruby

You might look into using the to_regexp gem; it doesn't use eval and it will allow you to do this:

 "/(abc|def)/i".to_regexp
# => /(abc|def)/i

Source at https://github.com/seamusabshere/to_regexp

Generate string for Regex pattern in Ruby

In Ruby:

/qweqwe/.to_s
# => "(?-mix:qweqwe)"

When you declare a Regexp, you've got the Regexp class object, to convert it to String class object, you may use Regexp's method #to_s. During conversion the special fields will be expanded, as you may see in the example., using:

(using the (?opts:source) notation. This string can be fed back in to Regexp::new to a regular expression with the same semantics as the original.

Also, you can use Regexp's method #inspect, which:

produces a generally more readable version of rxp.

/ab+c/ix.inspect        #=> "/ab+c/ix"

Note: that the above methods are only use for plain conversion Regexp into String, and in order to match or select set of string onto an other one, we use other methods. For example, if you have a sourse array (or string, which you wish to split with #split method), you can grep it, and get result array:

array = "test,ab,yr,OO".split( ',' )
# => ['test', 'ab', 'yr', 'OO']

array = array.grep /[a-z]/
# => ["test", "ab", "yr"]

And then convert the array into string as:

array.join(',')
# => "test,ab,yr"

Or just use #scan method, with slightly changed regexp:

"test,ab,yr,OO".scan( /[a-z]+/ )
# => ["test", "ab", "yr"]

However, if you really need a random string matched the regexp, you have to write your own method, please refer to the post, or use ruby-string-random library. The library:

generates a random string based on Regexp syntax or Patterns.

And the code will be like to the following:

pattern = '[aw-zX][123]'
result = StringRandom.random_regex(pattern)

eval certain regex from file to replace chars in string

While you can write something to parse that file, it rapidly gets complicated because you have to parse regular expressions. Consider /\/foo\\/.

There are a number of incomplete solutions. You can split on whitespace, but this will fail on /foo bar/.

re, replace = line.split(/\s+/, 2)

You can use a regex. Here's a first stab.

match = "/3/ 4".match(%r{^/(.*)/\s+(.+)})

This fails on escaped /, we need something more complex.

match = '/3\// 4'.match(%r{\A / ((?:[^/]|\\/)*) / \s+ (.+)}x)

I'm going to guess it was not your teacher's intent to have you parsing regexes. For the purposes of the assignment, splitting on whitespace is probably fine. You should clarify with your teacher.


This is a poor data format. It is non-standard, difficult to parse, and has limitations on the replacement. Even a tab-delimited file would be better.

There's little reason to use a non-standard format these days. The simplest thing is to use a standard data format for the file. YAML or JSON are the most obvious choices. For such simple data, I'd suggest JSON.

[
{ "re": "e", "replace": "3" },
{ "re": "l", "replace": "1" }
]

Parsing the file is trivial, use the built-in JSON library.

require 'json'
specs = JSON.load("test.json")

And then you can use them as a list of hashes.

specs.each do |spec|
# No eval necessary.
re = Regexp.new(spec["re"])

# `gsub!` replaces in place
result.gsub!(re, spec["replace"])
end

The data file is extensible. For example, if later you want to add regex options.

[
{ "re": "e", "replace": "3" },
{ "re": "l", "replace": "1", "options": ['IGNORECASE'] }
]

While the teacher may have specified a poor format, pushing back on bad requirements is good practice for being a developer.

How to combine these two Ruby string tests in one regular expression?

The most important improvement you can make is to also test that the word and the parentheseses have the correct relationship. If I understand correctly, "link(url link_name)" should be a match but "(url link_name)link" or "link stuff (url link_name)" should not. So match "link", the parentheses, and their contents, and capture the contents, all at once:

"stuff link(url link_name) more stuff".match(/link\((\S+?) (\S+?)\)/)&.captures
=> ["url", "link_name"]

(&. is Ruby 2.3; use Rails' .try :captures in older versions.)

Side note: string.scan(regex).present? is more concisely written as string =~ regex.

Ruby parse string with regular expressions


_, series, model = "[3 Series] 315".scan(/(\d+\s\w+|\d+)/)

OR

_, series, model = "[3 Series] 315".split /\[|\]\s/

series
# => "3 Series"
model
# => "315"

Create a case-insensitive regular expression from a string in Ruby

You can use Regexp.escape to escape all the characters in the string that would otherwise be handled specially by the regexp engine.

Regexp.new(Regexp.escape("A man + a plan * a canal : Panama!"), Regexp::IGNORECASE)

or

Regexp.new(Regexp.escape("A man + a plan * a canal : Panama!"), "i")

Select a string in regex with ruby

You can try an alternative approach: matching everything you want to keep then joining the result.

You can use this regex to match everything you want to keep:

[A-Z\d+| ^]|<?=>

As you can see this is just a using | and [] to create a list of strings that you want to keep: uppercase, numbers, +, |, space, ^, => and <=>.

Example:

"aA azee + B => C=".scan(/[A-Z\d+| ^]|<?=>/).join()

Output:

"A  + B => C"

Note that there are 2 consecutive spaces between "A" and "+". If you don't want that you can call String#squeeze.



Related Topics



Leave a reply



Submit