How to turn several "Sqrt [some text inside]" into several Sqrt (some text inside), I mean from [] to ()

I got the following expression that might look like this (the sum of Sqrt [XXX] is unknown)

Sqrt[A+B] + Sqrt[Min[A,B]] * Min[Sqrt[C],D] 

and I want to turn all Sqrt[XXX] into Sqrt(XXX) , I want to replace the brackets [] in Sqrt with () brackets

so the above example will look like

Sqrt(A+B) + Sqrt(Min[A,B]) * Min[Sqrt(C),D]

I donโ€™t want to โ€œharmโ€ the other brackets [] in the expression (for example, next to Min )

How to do this with regex?

+6
source share
2 answers

You can do this by iterating over characters in a String. First find the Sqrt[ index, and then find the matching closing bracket.

Here is a sample code:

 final String s = "Sqrt[A+B] + Sqrt[Min[A,B]] * Min[Sqrt[C],D]"; final char[] charArray = s.toCharArray(); int index = s.indexOf("Sqrt["); while (index != -1) { final int open = index + 4; charArray[open] = '('; // look for closing bracket int close; int matching = 0; for (close = open + 1; close < charArray.length; close++) { char c = charArray[close]; if (c == ']') { if (matching == 0) { break; } matching--; } else if (c == '[') { matching++; } } charArray[close] = ')'; index = s.indexOf("Sqrt[", index + 1); } System.out.println(new String(charArray)); 

I have not tested it correctly, so please do it.

+3
source

Using this format of the original string, you can do this with three regular expressions. The trick here is to โ€œrenameโ€ the square brackets belonging to the Min function and restore them later. You would do something like:

 s/Min\[([^[]+)\]/Min\{$1\}/g; s/Qsrt\[([^[]+)\]/Sqrt\($1\)/g; s/Min\{([^{]+)\}/Min\[$1\]}/g; 

In general, a parser might go. For special cases, such as using a trick, it may work :-).

+1
source

Source: https://habr.com/ru/post/904082/


All Articles