Modifying regexes

I recently had a very long regular expression that I needed two versions of, one for anywhere and one for just the end of a line. Handled!

RE = /long with a (capture) or (two)/
RE_AT_END = Regexp.new(RE.source + '$', RE.options)

This even works if the regular expression you’re modifying was created via something like Regexp.compile("(?i-mx:test)"), although it turns out a little ugly. In that case, I might (might) recommend:

Regexp.compile(RE.to_s.sub(/\)$/, '$)'))

1 Comment »

  1. Julianna said,

    August 18, 2007 @ 4:14 pm

    hi i enjoyed the read

RSS feed for comments on this post · TrackBack URI

Leave a Comment