Search code examples
c#regexcomplex-numbers

How should i get complex numbers from string?


I found following pattern from RegexLibrary, and i don't know how use Match to get Re and Im values. I'm new in Regex. Is it a correct way to get data from a pattern? If it's true, I need some sample code! This is what i think it should be:

public static complex Parse(string s)
{
    string pattern = @"([-+]?(\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?[r]?|[-+]?((\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?)?[i]|[-+]?(\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?[r]?[-+]((\d+\.?\d*|\d*\.?\d+)([Ee][-+]?[0-2]?\d{1,2})?)?[i])";
    Match res = Regex.Match(s, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);        

    // What should i do here? The complex number constructor is complex(double Re, double Im);

    // on error...
    return complex.Zero;
}

Thanks in advance!


Solution

  • I think they're overcomplicating the regex a bit, they are for example including support for scientific numbers and it seems that there are some errors in it.

    Try this simpler regex instead.

    class Program
    {
        static void Main(string[] args)
        {
            // The pattern has been broken down for educational purposes
            string regexPattern =
                // Match any float, negative or positive, group it
                @"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
                // ... possibly following that with whitespace
                @"\s*" +
                // ... followed by a plus
                @"\+" +
                // and possibly more whitespace:
                @"\s*" +
                // Match any other float, and save it
                @"([-+]?\d+\.?\d*|[-+]?\d*\.?\d+)" +
                // ... followed by 'i'
                @"i";
            Regex regex = new Regex(regexPattern);
    
            Console.WriteLine("Regex used: " + regex);
    
            while (true)
            {
                Console.WriteLine("Write a number: ");
                string imgNumber = Console.ReadLine();
                Match match = regex.Match(imgNumber);
    
                double real = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
                double img = double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
                Console.WriteLine("RealPart={0};Imaginary part={1}", real, img);
            }                       
        }
    }
    

    Remember to try to understand every regex you use, never use them blindly. They need to be understood like any other language.