正则表达式找到起始编号为8的数字

时间:2013-04-17 12:30:40

标签: c# .net regex

我的问题是我要构建一个检索PDF文档并打印文档的函数,我想要从8开始选择一个指定的数字。

输入:

"hello world, the number I want call is 84553741. help me plz."

正则表达式:

 String[] result = Regex.Split(Result, @"[^\d$]");

如何从号码8开始查找号码?

2 个答案:

答案 0 :(得分:1)

以下代码将从提供的输入字符串中提取以8开头的所有数字。

var input= "hello world, the number i want call is 84553741. help me plz.";
var matches = Regex.Matches(input, @"(?<!\d)8\d*");
IEnumerable<String> numbers = matches.Cast<Match>().Select(m=>m.Value);
foreach(var number in numbers)
{
    Console.WriteLine(number);
}

答案 1 :(得分:1)

现有的两个答案实际上并不匹配开始的数字与8,但包含的数字.8。然而匹配将从8开始。

要仅匹配以8开头的数字,您需要此正则表达式:

string[] testArray = new string[] { "test888", "test181", "test890", "test8" };
Regex regex = new Regex(@"(?<!\d)8\d*");

foreach (string testString in testArray)
{
    if (regex.IsMatch(testString))
        Console.WriteLine("\"{0}\" matches: {1}", testString, regex.Match(testString));
    else
        Console.WriteLine("\"{0}\" doesn't match", testString);
}

输出结果为:

"test888" matches: 888
"test181" doesn't match
"test890" matches: 890
"test8" matches: 8

使用正则表达式"8\d*"会产生以下结果:

"test888" matches: 888 // not mentioned results: 88 and 8
"test181" matches: 81  // obviously wrong
"test890" matches: 890
"test8" matches: 8