[OS X TeX] Find and replace with regular expressions

Matthew Leingang leingang at math.harvard.edu
Mon Nov 19 08:18:58 EST 2007


On Nov 19, 2007, at 7:20 AM, Alessandro Andretta wrote:

> I would like to replace the $ signs in a LaTeX file with \( and \)
> thus I would have to search for $...$ and replace it with \( ... \)
> where ... is any string of symbols (letters, numbers, \ , {} &,etc)
> EXCEPT $. I tried the help menu of TeXShop, TextMate, Textwrangler,
> but their general treatment seems be a bit too technical for my taste.
> Is there a simple way to archive this with any of the editors above?

Dear Alessandro,

Good question.  You need a more advanced search-and-replace  
capability that looks at the context, not just the string itself.   
This is what regular expressions [1] are for.

TeXShop has regular expression support built in.  So you can open up  
a find window,
put this in the search box

	\$([^$]+)\$

and this in the replace box

	\\(\1\\)

make sure you click "Regular Expressions," and go.

What that says is "look for any string that starts with a $, ends  
with a $, and has a string of at least one character, not including a  
$, in between.  Save what's in between."  The replace string says "\ 
(, then what was saved before, then \)."  The extra slashes are there  
because $ and \ have special meaning in regexps.  So the expression  
matches $A=a$, there's a match, and "A=a" is saved.

This will wreck your displayed math, though. An expression $$A=a$$  
will become $\(A=a\)$.  So if you have displayed math, do a regexp  
search and replace of
\$\$([^$]+)\$\$ with \\[\1\\] FIRST, or else you have to write a more  
complicated regexp to exclude displayed math.

I don't think this will get everything.  It may not get math  
expressions that span more than one line.  And if you use literal  
dollar signs in the text, if might replace everything BETWEEN your  
math expressions!  But it's a good start.  You can either write more  
regexps or hack away at the remaining ones each by each.

I would tread lightly here, especially if you're new to regexps.  You  
can destroy large parts of your file at once.  Backup a lot if the  
file is big.

HTH,
Matt

[1] http://en.wikipedia.org/wiki/Regular_expression


--
Matthew Leingang
Preceptor in Mathematics
Harvard University

http://www.math.harvard.edu/~leingang/vCard.vcf






More information about the MacOSX-TeX mailing list