我该如何从字符串中获取复数?

时间:2010-10-20 22:48:17

标签: c# regex complex-numbers

我从RegexLibrary找到了以下模式,我不知道如何使用Match来获取Re和Im值。我是Regex的新人。这是从模式中获取数据的正确方法吗? 如果这是真的,我需要一些示例代码! 这就是我认为它应该是:

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;
}

提前致谢!

3 个答案:

答案 0 :(得分:3)

我认为他们有点过于复杂的正则表达式,例如他们支持科学数字,似乎它有一些错误。

尝试使用这个更简单的正则表达式。

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);
        }                       
    }
}

请记住尝试了解您使用的每个正则表达式,不要盲目使用它们。他们需要像任何其他语言一样被理解。

答案 1 :(得分:1)

您需要从Capture获取2 Match个对象,并在其值上调用Double.Parse

顺便说一下,请注意,您应该使用static readonly Regex对象,这样每次调用Parse时都不需要重新解析模式。这将使您的代码运行得更快。

答案 2 :(得分:1)

这是我对Visual Basic .NET 4的看法:     

 

   Private Function GenerateComplexNumberFromString(ByVal input As String) As Complex 

 Dim Real As String = “(?<!([E][+-][0-9]+))([-]?\d+\.?\d*([E][+-][0-9]+)" & _
 "?(?!([i0-9.E]))|[-]?\d*\.?\d+([E][+-][0-9]+)?)(?![i0-9.E])”

 Dim Img As String = “(?<!([E][+-][0-9]+))([-]?\d+\.?\d*([E][+-][0-9]+)?" & _ 
 "(?![0-9.E])(?:i)|([-]?\d*\.?\d+)?([E][+-][0-9]+)?\s*(?:i)(?![0-9.E]))” 

 Dim Number As String = “((?<Real>(” & Real & “))|(?<Imag>(” & Img & “)))”
 Dim Re, Im As Double
 Re = 0
 Im = 0

  For Each Match As Match In Regex.Matches(input, Number)

      If Not Match.Groups(“Real”).Value = String.Empty Then
         Re = Double.Parse(Match.Groups(“Real”).Value, CultureInfo.InvariantCulture)
      End If

     If Not Match.Groups(“Imag”).Value = String.Empty Then
           If Match.Groups(“Imag”).Value.ToString.Replace(” “, “”) = “-i” Then
                  Im = Double.Parse(“-1″, CultureInfo.InvariantCulture)
           ElseIf Match.Groups(“Imag”).Value.ToString.Replace(” “, “”) = “i” Then
                  Im = Double.Parse(“1″, CultureInfo.InvariantCulture)
           Else
                  Im = Double.Parse(Match.Groups(“Imag”).Value.ToString.Replace(“i”, “”), CultureInfo.InvariantCulture)
  End If
  End If
 Next

     Dim result As New Complex(Re, Im)
      Return result
     End Function