Need simple regex for LaTeX
In my LaTeX files, I have literally thousands of occurrences of the following construct:
$\displaystyle{...math goes here...}$
I'd like to replace these with
\mymath{...math goes here...}
Note that the $'s disappear, but the curly braces remain---if not for the trailing $, this would be a basic find-and-replace. If only I knew any regex, I'm sure it would handle this with no problem. What's the regex I need to make this happen?
Many thanks in advance.
Edit: Some issues and questions have arisen, so let me clarify:
- Yes,
$\displaystyle{ ... }$
can occur multiple times on the same line. - No, nested
}$
's (such as$\displaystyle{...{more math}$...}$
) cannot occur. I mean, I suppose it could if you put it in an\mbox
or something, but I can't imagine why anyone would ever do that inside a$\displaystlye{}$
construct, the purpose of which is to display math inline with text. At any rate, it's开发者_如何转开发 not something I've ever done or am likely to do. - I tried using the perl suggestion, but while the shell raised no objections, the files remained unaffected.
- I tried using the sed suggestion, but the shell objected to an "unexpected token near `('". I've never used sed before (and "man sed" was obtuse), but here's what I did: navigated to a directory containing .tex files and typed "
sed s/\$\\displaystyle({[^}]+})\$/\\mymath\1/g *.tex
". No luck. How do I use sed to do what I want?
Again, many many thanks for all offered help.
Be very careful when using REGEX to do this type of substitution because the theoretical answer is that REGEX is incapable of matching this type of pattern.
REGEX is a finite state machine; it does not incorporate a pushdown stack so it cannot work with nested structures such as "{...math goes here...}" if there is any possibility of nesting such that something like "{more math}$" can appear as part of a "math goes here" string. You need at a minimum a context free grammar to describe this type of construct - a state machine just doesn't cut it!
Now having said that, you may still be able to pull this off using REGEX provided none of your "math goes here" strings are more complex than what a state machine can handle.
Give it a shot.... but beware of the results!
sed:
s/\$\\displaystyle({[^}]+})\$/\\mymath\1/g
perl -pi -e 's/$\\displaystyle({.*)}\$/\\mymath$1}/g' *.tex
if multiples }$ are on the same line you need a non greedy version:
perl -pi -e 's/$\\displaystyle({.*?)}\$/\\mymath$1}/g' *.tex
精彩评论