我有一个字符串,例如:
“12/11/2015:Liefertermin 71994:30.11.2015 -> 27.11.2015”
我想提取子字符串 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;
}
请您参考如下方法:
将 anchor ^ 和 $ 替换为单词边界 \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
但是,在方法内部创建正则表达式对象可能会变得效率低下。最好将其声明为静态私有(private)只读字段,然后在方法内部根据需要多次使用。
