I have strings with mathematical expressions like 2⁻¹² + 3³ / 4⁽³⁻¹⁾
.
I want to convert these strings to the form of 2^-12 + 3^3 / 4^(3-1)
.
What I got so far is that I can extract the superscript number and prepend the ^.
Fiddle of code below: https://dotnetfiddle.net/1G9ewP
using System;
using System.Text.RegularExpressions;
public class Program
{
private static string ConvertSuperscriptToText(Match m){
string res = m.Groups[1].Value;
res = "^" + res;
return res;
}
public static void Main()
{
string expression = "2⁻¹² + 3³ / 4⁽³⁻¹⁾";
string desiredResult = "2^-12 + 3^3 / 4^(3-1)";
string supChars = "([¹²³⁴⁵⁶⁷⁸⁹⁰⁺⁻⁽⁾]+)";
string result = Regex.Replace(expression, supChars, ConvertSuperscriptToText);
Console.WriteLine(result); // Currently prints 2^⁻¹² + 3^³ / 4^⁽³⁻¹⁾
Console.WriteLine(result == desiredResult); // Currently prints false
}
}
How would I replace the superscript characters without replacing each one of them one by one?
If I have to replace them one by one, how can I replace them using something like a collection similar to PHP's str_replace which accepts arrays as search and replace argument?
Bonus question, how can I replace all kinds of superscript characters with normal text and back to superscript?