【问题标题】:c# Split string that contains letters and numbersc#拆分包含字母和数字的字符串
【发布时间】:2015-03-24 20:31:59
【问题描述】:

我需要像这样拆分一个字符串:

string mystring = "A2";
mystring[0] "A" 
mystring[1] "2" 

string mystring = "A11";
mystring[0] "A" 
mystring[1] "11" 

string mystring = "A111";
mystring[0] "A" 
mystring[1] "111" 

string mystring = "AB1";
mystring[0] "AB" 
mystring[1] "1" 

我的字符串总是字母而不是数字,所以当字母完成时我需要拆分它。我只需要在这种情况下使用该号码。

我该怎么做?有什么建议吗?

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc-4 model-view-controller


    【解决方案1】:

    你可以使用正则表达式

    var parts = Regex.Matches(yourstring, @"\D+|\d+")
                .Cast<Match>()
                .Select(m => m.Value)
                .ToArray();
    

    【讨论】:

      【解决方案2】:

      Regex.Split 很容易做到。

      string input = "11A";
      Regex regex = new Regex("([0-9]+)(.*)");
      string[] substrings = regex.Split(input);
      

      【讨论】:

      • OP 发布字母然后数字。赞成最佳答案,但他的代码需要反向正则表达式
      • 您好,答案是对的,我在他回复的同时进行了编辑。我的错。
      【解决方案3】:

      您需要使用正则表达式来执行此操作:

      string[] output = Regex.Matches(mystring, "[0-9]+|[^0-9]+")
      .Cast<Match>()
      .Select(match => match.Value)
      .ToArray();
      

      【讨论】:

        猜你喜欢
        • 2013-09-30
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多