嗯,我知道这可能是C#的非常基本的功能。 但是我这么多年没用过了,所以问这个....
我有一个像MyName-1_1#1233
这样的字符串我想只选择 - ,_和#...
之间的数字/字符我可以使用分割功能,但它需要相当大的代码......还有什么吗?
从字符串中选择数字,我应该写如下代码
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...
}
答案 0 :(得分:1)
您可以使用正则表达式:
string S = "-1-2#123#3";
foreach (Match m in Regex.Matches(S, "(?<=[_#-])(\\d+)(?=[_#-])?"))
{
Console.WriteLine(m.Groups[1]);
}
答案 1 :(得分:0)
稍短一些:
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