gpt4 book ai didi

正则表达式仅返回七位数字匹配

转载 作者:行者123 更新时间:2023-12-04 21:34:53 25 4
gpt4 key购买 nike

我一直在尝试构建一个正则表达式来从字符串中提取一个 7 位数字,但很难让模式正确。

示例字符串 - WO1519641 WO1528113TB WO1530212 TB
示例返回 - 1519641, 1528113, 1530212
我在 Excel 中使用的代码是...

Private Sub Extract7Digits()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range

Set Myrange = ActiveSheet.Range("A1:A300")

For Each c In Myrange
strPattern = "\D(\d{7})\D"
'strPattern = "(?:\D)(\d{7})(?:\D)"
'strPattern = "(\d{7}(\D\d{7}\D))"

strInput = c.Value

With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With

If regEx.test(strInput) Then
Set matches = regEx.Execute(strInput)
For Each Match In matches
s = s & " Word: " & Match.Value & " "
Next
c.Offset(0, 1) = s
Else
s = ""
End If

Next
End Sub

我已经在该代码中尝试了所有 3 种模式,但最终得到 O1519641, O1528113T, O1530212 的返回使用 "\D(\d{7})\D" 时.据我所知, ()没有任何意义,因为我存储匹配项的方式,而我最初认为它们意味着表达式将返回 () 中的内容.

我一直在 http://regexr.com/ 上进行测试但我仍然不确定如何让它允许数字在字符串内作为 WO1528113TB只是返回数字。我是否需要对 RegEx 的返回值运行 RegEx 以第二次排除这些字母?

最佳答案

我建议使用以下模式:

strPattern = "(?:^|\D)(\d{7})(?!\d)"

然后,您将能够通过 (\d{7}) 访问捕获组 #1 的内容(即使用正则表达式的 match.SubMatches(0) 部分捕获的文本) ,然后您可以检查哪个值最大。

图案详情 :
  • (?:^|\D) - 与字符串开头 (^) 或非数字 (\D)
  • 匹配的非捕获组(不创建任何子匹配)
  • (\d{7}) - 捕获组 1 匹配 7 位
  • (?!\d) - 如果 7 位数字后面紧跟着一个数字,则匹配失败。
  • 关于正则表达式仅返回七位数字匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40890643/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com