From: Wesley J Landaker Date: 2003-05-31T03:26:53+09:00 Subject: regexp operators Hi folks, In doing some work with parsers the other day, I ended up with a situation where I wanted to embed and combine regexps easily, perserving any flags that they may have on them (such as case-sensitivity, etc). So I whipped this out really quick. It lets you combine regexp by adding them (+), ORing them (|) or by including them /blah#{some_regexp}blah/ inside each other, while preserving all flags. (At least, all flags that can be preserved--I can't do anything about the encodings if they mismatch... but I use all UTF-8 regexps, so I always use 'u'). This could potentially be extended to support other operations--but I haven't needed them yet on the project I'm tinkering with. Maybe this is useful or interesting to somebody besides me. ;) class Regexp @@inspect_regex = %r{/(.*)/((?:m|i|x)*)} def options return @@inspect_regex.match(self.inspect)[2] end def to_s self.inspect =~ @@inspect_regex if $2.length > 0 "(?#{$2}:#{$1})" else "(?:#{$1})" end end def |(other) /#{self}|#{other}/u end def +(other) /#{self}#{other}/u end end Super simple, but has been endlessly handy for me: $ irb irb(main):001:0> require 'RegexpOps' => true irb(main):002:0> /bar/ + /foo/ => /(?:bar)(?:foo)/u irb(main):003:0> /bar/i + /foo/ => /(?i:bar)(?:foo)/u irb(main):004:0> /bar/i + /foo/m => /(?i:bar)(?m:foo)/u irb(main):005:0> /bar/ix + /foo/m => /(?ix:bar)(?m:foo)/u irb(main):006:0> baz = /bar/i + /foo/ => /(?i:bar)(?:foo)/u irb(main):007:0> %r!foo#{/bar/i}*#{baz}?! => /foo(?i:bar)*(?:(?i:bar)(?:foo))?/ irb(main):008:0> /test/mi.options => "mi" And stuff like that. =) -- Wesley J. Landaker - wjl@icecavern.net OpenPGP FP: C99E DF40 54F6 B625 FD48 B509 A3DE 8D79 541F F830