Tania
Tania

Reputation: 11

How to make this regex non-greedy

String input = "<p>...<mfrac><mn>[format(((([[B]])*([[C]]))),\"###,##0.######\")]</mn><mn>[[D]]</mn></mfrac></math></p>";
String result = input.replaceAll("<mfrac>(<mn>\\[[^\\\\]+]</mn>)", "<mfrac><mrow>$1</mrow>");

Output:

<p>...<mfrac><mrow><mn>[format(((([[B]])*([[C]]))),"###,##0.######")]</mn><mn>[[D]]</mn></mrow></mfrac></math></p>

Wanted:

<p>...<mfrac><mrow><mn>[format(((([[B]])*([[C]]))),"###,##0.######")]</mn></mrow><mn>[[D]]</mn></mfrac></math></p>

How can I make the regex not greedy? I tried adding "?". Did not help. enter image description here

Upvotes: 0

Views: 54

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103913

With question marks, as the docs say. Evidently you didn't put the questionmark in the right place.

You have: input.replaceAll("<mfrac>(<mn>\\[[^\\\\]+]</mn>)", "<mfrac><mrow>$1</mrow>");
You need: input.replaceAll("<mfrac>(<mn>\\[[^\\\\]+?]</mn>)", "<mfrac><mrow>$1</mrow>");

Note that HTML isn't regular so none of this is a good idea. Use JSoup or a similar tool (something that parses html), modify the tree it gives you, re-render the tree back out to HTML, that's the right approach.

Upvotes: 1

Related Questions