Regexp查找起始号码为8的号码

本文关键字:号码 查找 Regexp | 更新日期: 2023-09-27 18:09:43

我的问题是,我即将构建一个函数,检索PDF文档并打印文档,我想挑选以8开头的指定数字。

输入:

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

Regexp:

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

如何查找以8开头的号码

Regexp查找起始号码为8的号码

下面的代码将从提供的输入字符串中提取所有以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);
}

已有的两个答案实际上并不匹配以8开头的数字,而是包含 8的数字。然而,匹配将从8开始。

只匹配以8开头的数字,您需要以下Regex:

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

使用Regex "8'd*"将产生以下结果:

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