I got the following Expression that can look like this (the amount of Sqrt[XXX] is unknow)
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 of the Sqrt
into ()
brackets
so the above example will look like
Sqrt(A+B) + Sqrt(Min[A,B]) * Min[Sqrt(C),D]
I don't want to "hurt" the other []
brackets in the expression (like the ones next to Min
)
How can I do it with regex ?
You can do this using iteration over the characters in the String. First look for the index of Sqrt[
and then look for the matching closing bracket.
Here is some 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 properly, so please do.
Using the given format of the source string, you can do it with 3 regular expressions. The trick here is to "rename" the square brackets belonging to the Min
function and restoring them later on. You would do something like:
s/Min\[([^[]+)\]/Min\{$1\}/g;
s/Qsrt\[([^[]+)\]/Sqrt\($1\)/g;
s/Min\{([^{]+)\}/Min\[$1\]}/g;
For the general case a parser would be the way to go. For special cases like this using a trick might work :-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With