I have this LaTeX code:

Lorem $math$ ipsum $math$dolor sit consecteruer adipscing elit,
sed do eiusmod tempor incidunt ut labore et dolore magna aliqua.
$math$Ut $math$ enim ad minim veniam$math$, quis nostrum exercitationem
ullamco laboriosam, $math$nisi ut aliquid ex ea commodi consequatur$math$.

I want to split math from following and preceeding text, that's to say, I want to replace




$math$ word

word $math$

So, I have tried with the following:

M-x query-replace-regexp RET \$\([^$]+?\)\$\\([^\S]\) RET $\1$ \2


M-x query-replace-regexp RET \([^S]\)\$\([^$]+?\) RET \1 $\2$

The problem is that these regularx expressions match too much than it is necessary.

Indeed, first replacement matches




"$math$ "




and only the first, second, third and sixth matches are necessary.

The second replacement matches:

" $math$"

" $math$"

"^J $match$"

" $math$"


" $math$"


and only the fifth and seventh matches are necessary.

How can I match only $math$word and word$math$?

  • isearch-forward-regexp will help designing your search regex. \s- will match a single whitespace character. \S- will match a single non-whitespace character. This is different from the perl-type regexes you may be used to. emacswiki.org/emacs/RegularExpression is an excellent page on Emacs-flavored regexes – nega Aug 21 at 14:58
  • re-builder/regexp-builder (they're aliases) will be helpful too. masteringemacs.org/article/… is a nice explainer. Note the magic C-c C-w command! – nega Aug 21 at 15:16
  • @nega I have tried with \([^ ]?\), \([^\s-]?\) and \([^\S-]?\), but they match too much cases, many of them are not necessary. isearch-forward-regexp is very useful and documentation on "masteringemacs.org" too! – Onner Irotsab Aug 22 at 7:46
  • This is not a regexp solution. But if you are asking because orgmode does not render $math$word, I wanted to point out that \(math\)word is rendered without issues. :) – Quarky Quanta Aug 24 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.