Use These Regular Expressions to Convert Your Views to Razor Without Quite So Much Typing


That Does It.

Today is the day. The day you finally throw down your hat and bid adieu to the angle-percents. The day you snatch hypertext from the jaws of awkwardly-indented awkwardness. Today you upgrade your ASP.NET MVC Views to Razor.

The gorgeous, buttery syntactical goodness of Razor. The seamless weaving of server code and HTML in a next-to-godliness codebase you’ve always known was possible, but was just out of—um.

Oh, right. Like you’re not a psychopath for clean code.

You, Sir! How About A Shave?

Here’s the thing. All that text editing? Thrilling, at first. You’re removing surplus characters, perhaps even debriding whole lines of code. Joy.

But then there’s another View. And another.

And now you’re not so much coding as chewing your cud with a keyboard.

The Razor’s Reg’

So here’s how you can tell that I care deeply for your well-being in a not-at-all creepy way, dear reader. I’ve baked up a batch of Find/Replace regular expression pairs that smell delightful and, when applied in the given order, will propel you most of the way through the ASPX-to-Razor shuffle.

Most of the way.

I’m a developer, not a lexer[1], and there will be constructs that have escaped my powers of prediction, lomticks of markup that are still a delimiter-confused mess, and bits with more hair than you would perhaps prefer. But that’s the twenty percent where you get out the nail scissors. The point here was to get to eighty as quickly as possible, and Vilfredo Pareto himself would likely shake his head if I frittered my afternoon on a more perfect automation for this one-time heave-ho.

It should be noted at this point that these regexes are strictly Visual Studio-brand, with plenty of subtle syntactical differing of opinion from the .NET regex engine you are likely accustomed to. It’s a good thing Jeff Atwood has already written all about this on Coding Horror.

And because a list of regex pairs might otherwise bore the tusks off an unsuspecting walrus, please feel free to pretend that the remainder of this post is actually two angry, angry cartoon characters swearing at each other.

Find: \<\%\@ Import Namespace=\”{.*}\” \%\>

Replace: @using \1;

F: \<\%[:|\=][:b]{[^\%]}[:b]*\%\>

R: @(\1)

F: \<\%[:b]}[:b][\%\>]*

R: }

F: {[:b]*\%\>

R: {

F: \<\%–

R: @*

F: –\%\>

R: *@

F: \<\%

R: @

F: [:b]+\@[:Wh]+

R:  @{

F: \%\>

R: }


  1. Dammit, Jim

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s