有比拆分函数更简单的方法吗

本文关键字:方法 更简单 函数 拆分 | 更新日期: 2023-09-27 18:20:47

好吧,我知道这可能是C#非常基本的功能。但我已经好几年没用了,所以问这个。。。。

我有一个类似MyName-1_1#1233 的字符串

我只想从-、_和#之间选择数字/字符。。。

我可以使用split函数,但它需要相当大的代码。。。还有别的吗?

为了从字符串中挑选数字,我应该像下面的代码一样写

string[] words = s.Split('-');
    foreach (string word in words)
    {
       //getting two separate string and have to pick the number using index... 
    }
  string[] words = s.Split('_');
    foreach (string word in words)
    {
       //getting two separate string and have to pick the number using index... 
    }
     string[] words = s.Split('#');
    foreach (string word in words)
    {
       //getting two separate string and have to pick the number using index... 
    }

有比拆分函数更简单的方法吗

您可以为此使用正则表达式:

        string S = "-1-2#123#3";
        foreach (Match m in Regex.Matches(S, "(?<=[_#-])(''d+)(?=[_#-])?"))
        {
            Console.WriteLine(m.Groups[1]);
        }

短一点:

    List<char> badChars = new List<char>{'-','_','#'};
    string str = "MyName-1_1#1233";
    string output = new string(str.Where(ch => !badChars.Contains(ch)).ToArray());

输出将是MyName111233

如果你只想要数字,那么:

    string str = "MyName-1_1#1233";
    string output = new string(str.Where(ch => char.IsDigit(ch)).ToArray());

输出将是111233