0
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

xerx593
  • 12,237
  • 5
  • 33
  • 64
Tania
  • 11
  • 2

1 Answers1

1

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Thank you. and how about this one? this one for replacing second "[[D]]" or first for the end ; result = result.replaceAll("(\\[[^\\\\]+])", "$1"); – Tania Sep 23 '22 at 16:10