trevmex's tumblings

Java Coder, JavaScripter, Rubyist, Functional Programmer, Agile Practitioner.

Insane regualr expression of the day

Remember kids, never put regexp in code, but it is fine if you are manipulating text in vim.

I love regexp. I think it is fun, and I hate editing big XML files by hand when I have to change a schema around (which happens sometimes). vim and the power of rexexp to the rescue!

See, I had to convert this:

<url><![CDATA[<%= "foo://five-by-#{2 + 3}/" %>]]></url>

into this:

<link id="the-foo" states="bar,baz">
<url><![CDATA[<%= "foo://five-by-#{2 + 3}/" %>]]></url>

almost got it on the first try. Two iterations later and I had the one-line solution:

:%s/\(<link\)\(>\n.*\n\).*<id>\([^<]*\).*\n\(.*\n\).*\n.*<member>\([^<]*\).*\n.*<member>\([^<]*\).*\n.*\n/\1 id="\3" states="\5,\6"\2\4/g

Awesome, right? That took me about five minutes to suss out.

This what the search looks like in regexper.

This is what the replace looks like.

There it is. One line saved me about thirty minutes of manual cutting and pasting AND the inevitable mistakes that come along with it.

And THAT is why everyone should learn regular expressions (but not for putting in code).