Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically remove anchors from a regular expression in Ruby?

Tags:

regex

ruby

Consider:

regex1 = /\A[a-z0-9\-\_]+\z/

regex2 = remove_anchors(regex1) # => /[a-z0-9\-\_]+/

How to implement a remove_anchors function that programmatically removes any anchors (\A, \z, ^, $) from regex1, producing regex2? Is it even possible to modify an existing regular expression like this in Ruby?

like image 626
XåpplI'-I0llwlg'I - Avatar asked Nov 19 '25 14:11

XåpplI'-I0llwlg'I -


1 Answers

You can use the following function:

def remove_anchors(regex)
   pattern = regex.source.gsub(/\A(?:\\A|\^)|(?:\\[zZ]|\$)\z/, '')
   return Regexp.new(pattern);
end

And here is an IDEONE demo

The regex literal notation /.../ compiles the regex and its string pattern can be obtained via the source property. With gsub, the anchors like ^, $, \A and \z can be removed from the string pattern.

like image 75
Wiktor Stribiżew Avatar answered Nov 22 '25 02:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!