识别数字串的序列

时间:2016-11-03 20:54:10

标签: c# .net .net-4.5

例如我们有这个字符串gf_T2fg57342523K_4212

我想拯救8个序列号,因此它将是57342523

另一个例子rt23A98457628Tr5462将是98457628

最好的原因是什么?

4 个答案:

答案 0 :(得分:5)

您可以使用匹配8位数的正则表达式:

var input = "gf_T2fg57342523K_4212";
var match = Regex.Match(input, @"\d{8}");

if (match.Success)
{
    var number = match.Value;
    //Do something
}

答案 1 :(得分:0)

您可以使用Regex进行此操作。

Regex regex = new Regex(@"\d{8}");
Match match = regex.Match("gf_T2fg57342523K_4212");

string value =  string.Empty;
if(match.Success) // If it is not important to know if it found something you cam suppress this if.
    value = match.Value;

答案 2 :(得分:0)

假设您要匹配仅包含 8个连续数字(而不是更多)的字符串,您将需要比其他答案中提供的更复杂的正则表达式。在这里,我使用了负面的后视和消极的前瞻:

(?<!\d)\d{8}(?!\d)

示例:

Regex.Match("gf_T2fg57342523K_4212", @"(?<!\d)\d{8}(?!\d)")
> Success, Value = "57342523"

Regex.Match("gf_T2fg111157342523K_4212", @"(?<!\d)\d{8}(?!\d)")
> Failure

有关外观分组结构的详细信息,请参阅msdn

答案 3 :(得分:-1)

var result = Regex.Matches(rt23A98457628Tr5462, @"\d{8}")
                    .Cast<Match>()
                    .Select(m => m.Value)
                    .ToList();
相关问题