我的正则表达式模式有问题:
我需要一个模式来提取精确的5连续数字
例A:123456789 dsadss12345 @ 3_- 1d22d333
例B:12345_ 2d2d2 aaa2222a
例C:2d2jj ddd_ @ 12345
通缉输出:12345
要么
(不是数字:“espace”;“letter”;“symbol:, - &etc”)(5个连续数字)(不是数字:“espace”;“letter”;“symbol:, - &etc”)
要么
(连续5个数字)(不是数字:“espace”;“letter”;“符号:, - &etc”)
要么
(不是数字:“espace”;“letter”;“符号:, - &etc”)(5个连续数字)
试过那些到目前为止:
(1)strPattern = "(((\s|\D|\W)(\d{5})(\s|\D|\W))|((\d{5})(\s|\D|\W))|((\s|\D|\W)(\d{5})))"
(2)strPattern = "\d{5}"
(3)strPattern = "(\s|\D|\W)(\d{5})(\s|\D|\W)"
(4)strPattern = "\D(\d{5})\D"
(3)不适用于Example
(2)不适用于ExampleS
(1)是我能得到的最好的,但它不会在很少的细胞中起作用。
我的正则表达式代码有什么好的模式?
你可以用
(?:^|\D)(\d{5})(?!\d)
(?:^|\D)
将匹配字符串的开头或除数字之外的任何字符,(\d{5})
将捕获5个数字到组1中,(?!\d)
将确保下一个字符不是数字。
示例代码:
Dim re, targetString, colMatch, objMatch
Set re = New regexp
With re
.pattern = "(?:^|\D)(\d{5})(?!\d)"
.Global = True ' Same as /g at the online tester
End With
targetString = "123456789 dsadss12345@3_- 1d22d333"
Set colMatch = re.Execute(targetString)
For Each objMatch In colMatch
Debug.Print objMatch.SubMatches.Item(0)
Next
这通过了OP中概述的所有测试:
((?<!\d)\d{5}(?!\d))
完全匹配只有5个连续数字,除了数字之外的任何东西都包围
证据是在布丁: