【发布时间】:2017-09-12 11:53:00
【问题描述】:
我正在尝试使用 RegEx 或 LINQ 获取字符串中的 最后 2 位数字。 例如我得到了这些字符串:
N43OET28W -> result should be 28
N1OET86W -> result should be 86
S02CT55A -> result should be 55
M4AKT99A -> result should be 99
1W24ET39W -> result should be 39
S03KT45A -> result should be 45
M1AKT23A -> result should be 23
N1OET35W -> result should be 35
N12FET42W -> result should be 42
MAKTFDAAD -> result should be null or 0
N3XUK407Q -> result should be 07
MAKT23A -> result should be 23
现在我尝试了这段代码:
getIntPattern("N1WET99W");
getIntPattern("S03KT45A");
getIntPattern("M1AKT23A");
getIntPattern("N1OET35W");
getIntPattern("N1OET42W");
getIntPattern("MAKTFDAAD");
getIntPattern("N12FET42W");
private int getIntPattern(string text)
{
int result = 0;
string m = Regex.Matches(text, @".*?\d+.*?(\d+)")
.Cast<Match>()
.Select(match => match.Groups[1].Value).First();
int.TryParse(m, out result);
return result;
}
有没有更好的方法来实现这一点?输入字符串的长度不同,开头可以包含更多数字。我只需要最后两位数。
【问题讨论】:
-
请问
"ABC12DEF456XY"的预期输出是多少(12或45或56)? -
只有最后2位,这里是56
-
如果最后两位数字被非数字分隔怎么办?
W875W6会产生什么? -
如果您正在寻找更好的答案,那么不应该将其发布在 codereview.stackexchange.com 上吗?
-
@juharr:XYZ5A2 无效。我必须是 2 位数字或 null/false