c#正则表达式查找并提取给定长度的数量

时间:2015-11-13 09:09:54

标签: c# regex

我有一个字符串,如:

" 12/11/2015:Liefertermin 71994:30.11.2015 - > 2015年11月27日"

我想提取子串71994,它总是5位数

我尝试过以下操作但没有成功:

 private string FindDispo_InInfo()
    {
        Regex pattern = new Regex("^[0-9]{5,5}$");
        Match match = pattern.Match(textBox1.Text);

        string stDispo = match.Groups[0].Value;
        return stDispo;
    }

2 个答案:

答案 0 :(得分:6)

将锚点^$替换为单词边界\b并使用逐字字符串文字:

Regex pattern = new Regex(@"\b[0-9]{5}\b");

您可以使用match.Value访问该值:

string stDispo = match.Value;

固定代码:

private static string FindDispo_InInfo(string text)
{
    Regex pattern = new Regex(@"\b[0-9]{5}\b");
    Match match = pattern.Match(text);
    if (match.Success)
        return match.Value;
    else
        return string.Empty;
}

这是一个C# demo

Console.WriteLine(FindDispo_InInfo("12/11/2015: Liefertermin 71994 : 30.11.2015 -> 27.11.2015"));
// => 71994

但是,在方法中创建正则表达式对象可能效率低下。最好将其声明为静态私有只读字段,然后根据需要在方法内部使用多次。

答案 1 :(得分:3)

你需要的是(\d{5}),它将捕获一些长度为5的

相关问题