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:

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

into this:

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

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).