gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:02 27 4
gpt4 key购买 nike

我有一个字符串,例如:

“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)只读字段,然后在方法内部根据需要多次使用。

关于c#正则表达式查找并提取给定长度的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com