正则表达模式难度

问题描述 投票:3回答:3

我的正则表达式模式有问题:

我需要一个模式来提取精确的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)是我能得到的最好的,但它不会在很少的细胞中起作用。

我的正则表达式代码有什么好的模式?

regex excel vba
3个回答
3
投票

你可以用

(?:^|\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

2
投票

RegEx Cheat Sheet

它本身并不是一个真正的答案,但我认为这个优秀的总结是值得的(在这里更容易分享!)

单击图像以查看完整大小。


1
投票

这通过了OP中概述的所有测试:

((?<!\d)\d{5}(?!\d))

完全匹配只有5个连续数字,除了数字之外的任何东西都包围

证据是在布丁:

https://regex101.com/r/Oz2aeR/1

© www.soinside.com 2019 - 2024. All rights reserved.