gpt4 book ai didi

regex - 查找字符串中的第一个数字,可能是 1,11,111

转载 作者:行者123 更新时间:2023-12-04 20:45:07 24 4
gpt4 key购买 nike

我正在循环使用这种模式的文件名 name_name-number-name_name.txt
我需要提取 number .

例如,

  • 来自 xxx_xx-111-ssadas22我会得到 111 .
  • 来自 xxx_xx-11-sadaesdwsq4443fsd2我会得到 11

  • 目前正在使用它,但是当名称中有数字时它就不足了。还尝试了正则表达式,但不擅长。
    Function FirstDigit(strData As String) As Integer
    Dim RE As Object
    Dim REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
    .Pattern = "(^|\\s)([0-100]+)($|\\s)"
    End With

    Set REMatches = RE.Execute(strData)
    FirstDigit = REMatches.item(0)
    End Function

    任何想法 ?

    最佳答案

    尝试这个:

    Function FirstDigit(strData As String) As Integer
    Dim RE As Object
    Dim REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
    .Pattern = "\b[^_\s]+_[^-\s]+-(\d+)-[^\.\s]+\.txt\b"
    End With

    Set REMatches = RE.Execute(strData)
    If REMatches.Count > 0 Then
    FirstDigit = REMatches(0).SubMatches(0)
    Else
    FirstDigit = -1 '' or whatever you want to output when there is no match
    End If
    End Function

    测试:
    Sub Test()
    Debug.Print FirstDigit("xxx_xx-1-ssadas22.txt") '' Returns 1
    Debug.Print FirstDigit("xxx_xx-11-ssadas22.txt") '' Returns 11
    Debug.Print FirstDigit("xxx_xx-111-ssadas22.txt") '' Returns 111
    Debug.Print FirstDigit("xxx_xx-asasa-ssadas22.txt") '' Returns -1 (no match)
    End Sub

    关于regex - 查找字符串中的第一个数字,可能是 1,11,111,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455457/

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