pen*_*ake 3 .net c# regex string parsing
我有一些字符串:"7d","5m","95d"等.
我需要找到简单的方法来分别获得整数和char.
我怎样才能做到这一点:
int number = GetNumber("95d"); //should return 95
char code = GetCode("95d"); // should return d
Run Code Online (Sandbox Code Playgroud)
这些是表达式:
[^\d]+ <- not digit
\d+ <- digits
Run Code Online (Sandbox Code Playgroud)
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';
}
Run Code Online (Sandbox Code Playgroud)
您实际上只需要创建RegExp一次该对象,而不是每次方法调用.
| 归档时间: |
|
| 查看次数: |
1091 次 |
| 最近记录: |