提取与正则表达式vb.net匹配的字符串

时间:2018-07-01 01:42:18

标签: regex vb.net

我的文字如下

1.
2.
3.
4. Test data 1
Please identify the ID number:
# 1016108
Please check if the number above matches the number below. The comparison result
should be "True or False". You should only compare the 7 digits:
a. #1016108
Please try to compare the results from Google OCR Engine and Microsoft OCR Engine.
And choose the one that suits for this task better.
Here is a third number # 123456, please DO NOT use this number for this task

我需要提取数字,其后仅是#,而不是第三个数字,因为它前面有一个文本“第三个数字”。也有人提到我不应该用这个数字来匹配。所以我需要提取前两个数字(仅数字)并匹配并说出结果。

注释中的代码

Dim mc As MatchCollection
Dim i As Int32
mc = Regex.Matches(txt, "[#]([0-9]+)")
Dim results(mc.Count - 1) As String
For i = 0 To results.Length - 1
    results(i) = mc(i).Value
Next
MessageBox.Show(results.ElementAt(0).ToString)

3 个答案:

答案 0 :(得分:0)

您可能要做的是匹配不需要的内容,并使用alternation在组中捕获您想要的内容。您的值将在捕获的组1中。

\bthird number\s*\#\s*\d+\b|#\s*(\d+)\b

Demo

说明

  • \bthird number\s*\#\s*\d+\b匹配third number,然后加上单词边界\b,以确保第三个字符不是较长匹配的一部分,然后是#,零个或多个空白字符之间{ {1}}
  • \s*
  • |匹配#\s*(\d+)\b,零个或多个空格字符,并捕获一个或多个数字#,后跟一个单词边界

或者您可以在正后使用负号来断言左侧的不是第三个数字:

(?<!\bthird number\s*#\s*)(?<=#\s*)\d+\b

Demo

说明

  • \d+断言左边(?<!\bthird number\s*#\s*)的前面没有单词边界third number,以确保第三个不是较长匹配的一部分,然后是{{1} },零个或多个空白字符\b
  • 之间
  • #断言左侧是\s*,后跟零个或多个空格字符
  • (?<=#\s*)匹配一个或多个数字,后跟一个单词边界

您可以使用#而不是\d+\b而不是仅匹配third来匹配一个或多个非空白字符。

答案 1 :(得分:0)

Dim mc As system.Text.RegularExpressions.MatchCollection

将i视作Int32     mc = system.Text.RegularExpressions.Regex.Matches(txt,“ ^#\ s?”)

Dim results(mc.Count - 1) As String
For i = 0 To results.Length - 1
    results(i) = mc(i).Value

Next
enter code here

答案 2 :(得分:-1)

按照您的模式,如果我对您的理解是正确的,则仅在#之前没有写“第三个数字”时,才希望#之后的数字

在这种情况下,此简单的正则表达式应该起作用,请检出this

这是那些不想遵循链接的正则表达式:#(。 \ n | \ s。 \ n)

这是假设您想要的#末尾有一个新行,从您发布的示例文本中可以看到。

这还将解决在#后面可能有空格的不一致之处。