Project

to_regexp

0.33
No commit activity in last 3 years
No release in over 3 years
Provides String#to_regexp, for example if you want to make regexps out of a CSV you just imported.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

 Project Readme

to_regexp¶ ↑

Basically a safe way to convert strings to regexps (with options).

str = "/finalis(é)/im"
old_way = eval(str)     # not safe
new_way = str.to_regexp # provided by this gem
old_way == new_way      # true

You can also treat strings as literal regexps. These two are equivalent:

'/foo/'.to_regexp                                       #=> /foo/
'foo'.to_regexp(:literal => true)                       #=> /foo/

If you need case insensitivity and you’re using :literal, pass options like :ignore_case. These two are equivalent:

'/foo/i'.to_regexp                                      #=> /foo/i
'foo'.to_regexp(:literal => true, :ignore_case => true) #=> /foo/i

You can get the options passed to Regexp.new with #as_regexp:

'/foo/'.to_regexp == Regexp.new('/foo/'.as_regexp) # true

Finally, you can be more lazy using :detect:

'foo'.to_regexp(detect: true)     #=> /foo/
'foo\b'.to_regexp(detect: true)   #=> %r{foo\\b}
'/foo\b/'.to_regexp(detect: true) #=> %r{foo\b}
'foo\b/'.to_regexp(detect: true)  #=> %r{foo\\b/}

Copyright 2012 Seamus Abshere