I have a string and would like to replace all instances of the two characters "<" and ">" together with all its surrounding whitespace (no tabs, no newlines, possibly empty) by " < " and " > ", respectively.
Can I do this with a one-liner replace regex expression?
The slow and hard way would be
while (entry.value.indexOf(" <") > -1) {
entry.value = entry.value.replace(" <","<");
}
while (entry.value.indexOf("< ") > -1) {
entry.value = entry.value.replace("< ","<");
}
while (entry.value.indexOf(" >") > -1) {
entry.value = entry.value.replace(" >",">");
}
while (entry.value.indexOf("> ") > -1) {
entry.value = entry.value.replace("> ",">");
}
entry.value = entry.value.replace("<"," < ").replace(">"," > ");
Shortening the whitespace is explained at Regex to replace multiple spaces with a single space, but I do not assume whitespaces around the two characters.
The use case I have are saving math expressions in a database to be presented on a website using MathJax. Doing so, one runs into exactly this problem, see http://docs.mathjax.org/en/latest/tex.html#tex-and-latex-in-html-documents.
Typical expressions are
"Let $i$ such that $i<j$..."
"Let $<I>$ be an ideal in..."
(the later wouldn't even render here in the preview in normal text mode.)