Can C# detect exponents like 2² , 2³ not the ones with carets(^)

Kalyan A 440 Reputation points
2024-10-10T13:58:21.0633333+00:00

Can C# detect exponents like 2² , 2³ not the ones with carets(^).

I want to detect 2³ and write Base =2 Exponent=3

The below code is from Copilot , It cannot detect 2²

using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
        string input = "The result of 2³ is eight.";
        Regex regex = new Regex(@"(\d+)\^(\d+)");
        Match match = regex.Match(input);
        if (match.Success)
        {
            int baseNum = int.Parse(match.Groups[1].Value);
            int exponent = int.Parse(match.Groups[2].Value);
            Console.WriteLine($"Base: {baseNum}, Exponent: {exponent}");
        }
        else
        {
            Console.WriteLine("No match found.");
        }
    }
}
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2024-10-10T14:33:58.8233333+00:00

    Try this:

    string input = "The result of 2³ is eight.";
    Regex regex = new Regex( @"(\d+)([\xB2\xB3\xB9\u2070\u2074-\u2079]+)" );
    Match match = regex.Match( input );
    if( match.Success )
    {
        int baseNum = int.Parse( match.Groups[1].Value );
        int exponent = int.Parse( match.Groups[2].Value.Normalize( NormalizationForm.FormKC ) );
        Console.WriteLine( $"Base: {baseNum}, Exponent: {exponent}" );
    }
    else
    {
        Console.WriteLine( "No match found." );
    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.