C#为什么我不能拆分字符串?

ret*_*ide 2 c# regex

 string myNumber = "3.44";

       Regex regex1 = new Regex(".");

       string[] substrings = regex1.Split(myNumber);

        foreach (var substring in substrings)
        {
            Console.WriteLine("The string is : {0} and the length is {1}",substring, substring.Length);
        }

        Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

我试图用"."拆分字符串,但是拆分返回4个空字符串.为什么?

Jon*_*eet 27

.表示正则表达式中的"任何字符".所以不要使用正则表达式进行拆分 - 使用String.Split以下方法拆分:

string[] substrings = myNumber.Split('.');
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用正则表达式,你可以使用:

Regex regex1 = new Regex(@"\.");
Run Code Online (Sandbox Code Playgroud)

@使其成为一个逐字字符串,从具有转义反斜线阻止你.字符串本身内的反斜杠是正则表达式解析器中点的转义.

  • @retide:我给了两个建议,一个是因为你有什么理由你没有告诉我们使用正则表达式,一个如果你没有...如果你不需要*使用正则表达式,为什么这样做? (2认同)

Joh*_*Woo 6

最简单的解决方案是: string[] val = myNumber.Split('.');