danlucraft /blog

Regex Replacer

May 2008 • Daniel Lucraft

Here is a little Ruby library that may be useful to you. It is a regular expression string replacing tool. It’s similar to what you can do with String#gsub in Ruby, but with a few more features.

I needed this library to get Textmate snippets working in Redcar, and therefore it uses a slightly different syntax to gsub (“$1” instead of “\1”). Here are some examples:

rr = RegexReplace.new(/nuclear (\w+)/, "solar $1")
  rr.rep("nuclear nutcracker")
  => "solar nutcracker"

So far so obvious. That’s identical to Ruby gsub but with “\1” changed to “$1”. Here’s something more useful:

rr = RegexReplace.new(/nuclear (\w+)/, "solar \\u$1")
  rr.rep("nuclear nutcracker")
  => "solar Nutcracker"

Whee! Letters following “\u” are upcased. What else can it do?

Upcase stretches with \U…\E

rr = RegexReplace.new(/nuclear (\w+)/, "solar \\U$1\\E")
  rr.rep("nuclear nutcracker")
  => "solar NUTCRACKER"

You can downcase in exactly the same way with “\l” and “\L..\E”.

Conditional replacement with (?1:then:else)

rr = RegexReplace.new(/nuclear( \w+)?/, "solar(?1:$1: thingy)")
  rr.rep("nuclear nutcracker")
  => "solar nutcracker"
  
  rr.rep("nuclear")
  => "solar thingy"

You can also combine the operators in this fashion “\l\U…\E” to get (for instance) “fOO” from “foo”.

If you find it useful please let me know.

blog comments powered by Disqus