我需要一个模式来仅提取五个连续的数字。
示例A:123456789 dsadss12345@3_- 1d22d333
示例B:12345_ 2d2d2 aaa2222a
示例C:2d2jj ddd_@12345
想要的输出:12345
或
(非数字:“espace”;“字母”;“符号:,-& 等”)(5 个连续数字)(非数字:“espace”;“字母”;“符号:,-& 等等”)
或
(5个连续数字)(非数字:“espace”;“字母”;“符号:,-&等”)
或
(非数字:“espace”;“字母”;“符号:,-& 等”)(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) 不适用于示例 B
(2) 不适用于示例A
(1) 是我能得到的最好的结果,但它在少数单元格中不起作用。
最佳答案
您可以使用
(?:^|\D)(\d{5})(?!\d)
参见 regex demo 。
(?:^|\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
关于regex - 仅适用于五个连续数字的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52171516/