>我有如下文字
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
我需要单独提取后跟 # 的数字,而不是第三个数字,因为它前面有一个文本"第三个数字"。 还提到我不应该拿这个数字进行匹配。 所以我需要提取前 2 个数字(仅限数字(并匹配并说出结果.
来自注释的代码
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)
你可以做的是匹配你不想要的东西,并使用交替在一个组中捕获你想要的东西。您的值将位于捕获的组 1 中。
bthird numbers*#s*d+b|#s*(d+)b
演示
解释
bthird numbers*#s*d+b
Matchthird number
前面有一个单词边界b
,以确保第三个不是较长匹配的一部分,后跟零个或多个空格字符之间的#
s*
|
或#s*(d+)b
匹配#
、零个或多个空格字符,并在一组中捕获一个或多个数字d+
后跟单词边界
或者,您可以使用正面和负面的回溯来断言左侧的内容不是第三个数字:
(?<!bthird numbers*#s*)(?<=#s*)d+b
演示
解释
(?<!bthird numbers*#s*)
断言左侧的内容third number
前面没有单词边界b
以确保第三个不是较长匹配的一部分,后跟零个或多个空格字符之间的#
s*
(?<=#s*)
断言左侧的内容#
后跟零个或多个空格字符d+b
匹配一个或多个数字,后跟单词边界
您可以使用S+ number
而不是bthird number
来匹配一次或多次非空格字符,而不是仅匹配third
。
Dim mc As system.Text.RegularExpressions.MatchCollection
dim i 饰 Int32 mc = 系统。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
遵循您的模式,如果我理解正确,您只需要 # 后面的数字,前提是 # 之前没有写"第三个数字">
在这种情况下,这个简单的正则表达式应该可以,请查看此内容
这是那些不想点击链接的人的正则表达式:#(。|\s.(
这假设您想要的 # 末尾会有一个新行,从您发布的示例文本中可以看出。
这也将处理 # 之后可能存在空格的不一致