Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从字符串中获取复数?_C#_Regex_Complex Numbers - Fatal编程技术网

C# 如何从字符串中获取复数?

C# 如何从字符串中获取复数?,c#,regex,complex-numbers,C#,Regex,Complex Numbers,我从中发现了以下模式,我不知道如何使用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][-+]?[

我从中发现了以下模式,我不知道如何使用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;
}

提前谢谢

您需要从
Match
中获取2个
Capture
对象,并调用
Double.Parse对其值进行分析


顺便注意,您应该使用
静态只读Regex
对象,这样它就不需要在每次调用
parse
时重新解析模式。这将使您的代码运行得更快。

您需要从
匹配中获取2个
捕获
对象,并调用
Double.Parse


顺便注意,您应该使用
静态只读Regex
对象,这样它就不需要在每次调用
parse
时重新解析模式。这将使您的代码运行得更快。

我认为他们有点过于复杂化了正则表达式,例如,它们包括对科学数字的支持,而且似乎其中有一些错误

试试这个更简单的正则表达式

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

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

我认为它们有点过于复杂化了正则表达式,例如,它们包含了对科学数字的支持,似乎其中有一些错误

试试这个更简单的正则表达式

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

记住试着理解你使用的每一个正则表达式,不要盲目地使用它们。它们需要像其他语言一样被理解。

这是我对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

私有函数GenerateComplexNumberFromString(ByVal输入为字符串)作为复数

Dim Real As String=“(?(“&Real&”)|(?(“&Img&”))
我是双重身份
Re=0
Im=0
将每个匹配作为Regex.Matches中的匹配(输入,编号)
如果不匹配.Groups(“Real”).Value=String.Empty,则
Re=Double.Parse(Match.Groups(“Real”).Value,CultureInfo.InvariantCulture)
如果结束
如果不匹配.Groups(“Imag”).Value=String.Empty,则
如果Match.Groups(“Imag”).Value.ToString.Replace(“,”)=“-i”,则
Im=Double.Parse(“-1”,CultureInfo.InvariantCulture)
ElseIf Match.Groups(“Imag”).Value.ToString.Replace(“,”)=“i”然后
Im=Double.Parse(“1〃,CultureInfo.InvariantCulture)
其他的
Im=Double.Parse(Match.Groups(“Imag”).Value.ToString.Replace(“i”),CultureInfo.InvariantCulture)
如果结束
如果结束
下一个
作为新复合体的Dim结果(Re、Im)
返回结果
端函数

这是我对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

私有函数GenerateComplexNumberFromString(ByVal输入为字符串)作为复数

Dim Real As String=“(?(“&Real&”)|(?(“&Img&”))
我是双重身份
Re=0
Im=0
将每个匹配作为Regex.Matches中的匹配(输入,编号)
如果不匹配.Groups(“Real”).Value=String.Empty,则
Re=Double.Parse(Match.Groups(“Real”).Value,CultureInfo.InvariantCulture)
如果结束
如果不匹配.Groups(“Imag”).Value=String.Empty,则
如果Match.Groups(“Imag”).Value.ToString.Replace(“,”)=“-i”,则
Im=Double.Parse(“-1”,CultureInfo.InvariantCulture)
ElseIf Match.Groups(“Imag”).Value.ToString.Replace(“,”)=“i”然后
Im=Double.Parse(“1〃,CultureInfo.InvariantCulture)
其他的
Im=Double.Parse(Match.Groups(“Imag”).Value.ToString.Replace(“i”),CultureInfo.InvariantCulture)
如果结束
如果结束
下一个
作为新复合体的Dim结果(Re、Im)
返回结果
端函数

哦!我知道错误时返回零是错误的!我稍后会处理它!请不要告诉我这件事!;)哦!我知道错误时返回零是错误的!我稍后会处理它!请不要告诉我这件事!;)谢谢!但输入字符串可能类似于以下值:2或2i或2+3i……我应该在separa中分离这些情况吗te模式?我太懒了,不想解析那个庞大的正则表达式;看看你能不能弄清楚它的组是如何工作的,或者你能不能自己编写正则表达式。我怀疑抛弃正则表达式,自己编写解析器会更容易。是的!你说得对!这是一个非常庞大的正则表达式!!!如果更简单的话,我会尝试自己的解析器!:)谢谢!但输入字符串可以就像这些值一样:2或2i或2+3i和…我应该以不同的模式分离这些情况吗?我太懒了,无法解析那个庞大的正则表达式;看看你是否能弄清楚它的组是如何工作的,或者是否能编写自己的正则表达式。我怀疑抛弃正则表达式并编写自己的解析器会更容易。是的!你的权利!这是一个非常庞大的正则表达式n!!!如果更简单的话,我会尝试我自己的解析器!:)谢谢!和+1表示“理解你使用的每个正则表达式,不要盲目使用它们”。我会记住它;)谢谢!和+1表示“理解你使用的每个正则表达式,不要盲目使用它们。”我会记住它;)