我有这样的字符串:“7d”、“5m”、“95d”等。
我需要找到一个简单的方法来分别得到整数和字符。
我怎样才能做到这一点:
int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d
最佳答案
这些是表达式:
[^\d]+ <- not digit
\d+ <- digits
编辑
static int GetNumber(string text)
{
string pat = @"\d+";
int output;
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(text);
if (int.TryParse(m.Value, out output))
return output;
else
return int.MinValue; // something unlikely
}
static char GetChar(string text)
{
string pat = @"[^\d]";
int output;
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(text);
return m.Value.Length == 1 ? m.Value[0] : '\0';
}
您实际上只需要创建一次 RegExp
对象,而不是在每次方法调用时都创建一次。
关于c# - 如何在这样一个简单的字符串中分别获取整数和字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638432/