Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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 ?

like image 344
Daniel Avatar asked Dec 19 '11 14:12

Daniel


2 Answers

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.

like image 58
dogbane Avatar answered Oct 19 '22 08:10

dogbane


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 :-).

like image 22
rsp Avatar answered Oct 19 '22 08:10

rsp