Some tricky regular expression for search and replace in Kile

I have always wanted to learn regular expression comprehensively, but the task of rote memory always daunts me. Today I finally had some courage to experiment with it in the simplest setting, namely doing a search and replace in kile: one of the most sophisticated latex environments.

I want to replace all occurrences of “a_” with “\tilde{a}_”. But searching for just a_ is ambiguous since it would include also things like \theta_ and \lambda_ ; indeed almost the entire Greek alphabet.

So what I was looking for is something like [non-alphabet]a_ and replace it with #1a_, where #1 should stand for the first matching character in the search query.

It turns out the correct syntax is

search for: ([^a-z])a_

replace by: \1\\tilde{a}_

The main thing I want to point out, which is missing from wikipedia page on regex, is how to implement placeholder for replacement. Here we used the escaped sequence “\1”, one can also do “\2”, “\3” etc, in any order; it is mandatory to surround the source of the replacement by parentheses, which in this case is the substring “(^[a-z])”. The sequence “” has a special meaning, which is to replace matching substring of arbitrary length. It does not require parentheses around the source string in the search query.

Also for starters, the double slashes substring “\\tilde” is necessary since “\” is a special symbol. The “[a-z]” matches a single character in the range a-z, and the caret “^” inside takes the complement of that set. These details can be easily gleaned from wiki and other standard online sources on regex.

For more detail see this excellent article:
http://www.codeguru.com/cpp/cpp/string/regex/article.php/c2791

Advertisements

About aquazorcarson

math PhD at Stanford, studying probability
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Some tricky regular expression for search and replace in Kile

  1. Louis says:

    I find your Latex Kile regexp tips quite useful. Thank you !

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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