【问题标题】:Extract text which begin with the same two characters and end in a numeric character提取以相同的两个字符开头并以数字字符结尾的文本
【发布时间】:2023-03-23 03:25:01
【问题描述】:

我想从更大的文本提取中提取代码,我拥有的常量是代码将以 WP 或 MD 开头并以数字值结尾,代码可以使用的模式示例如下;

WP0053

WP053

WP_053

WP_0053

WP 053

WP 0053

MDC_308

WP6

WP6.1

MDC_0308

请看下面预期输出的图片;

任何帮助将不胜感激

【问题讨论】:

  • 如果它总是以项目 id 后跟下划线开头,您可以将其替换为空字符串。您想要的代码将位于剩余字符串的开头。之后,使用空格作为分隔符进行拆分并获取第一个标记。
  • 您应该发布您尝试过的任何内容。这不是代码编写服务,而是帮助修复损坏的代码。

标签: regex vba excel user-defined-functions udf


【解决方案1】:

公共函数GetCode(data As String) As String

startpos = InStr(data, "WP")
If startpos = 0 Then startpos = InStr(data, "MD")

fisrtNumPos = 0
For i = startpos To Len(data)

    If fisrtNumPos = 0 And LastNumPos = 0 Then
        If IsNumeric(Mid(data, i, 1)) Then
            fisrtNumPos = i
        End If
    Else
        If Not IsNumeric(Mid(data, i, 1)) Then
            LastNumPos = i
            Exit For
        End If
    End If
Next i

Endpos = LastNumPos - startpos

GetCode = Mid(data, startpos, Endpos)

结束函数

将此代码添加到任何模块中并尝试。

【讨论】:

    【解决方案2】:

    如果您的代码没有空间,那么下面的代码会有所帮助。

    子测试()

    Data = "A850085_MDC-WP-01003_SRI Phase 2 - Programme Manager - Dionysios Psachoulias"
    
    startpos = InStr(Data, "WP")
    If startpos = 0 Then startpos = InStr(Data, "MD")
    
    fisrtNumPos = 0
    LastNumPos = 0
    For i = startpos To Len(Data)
    
        If fisrtNumPos = 0 And LastNumPos = 0 Then
            If IsNumeric(Mid(Data, i, 1)) Then
                fisrtNumPos = i
            End If
        Else
            If Not IsNumeric(Mid(Data, i, 1)) Then
                LastNumPos = i
                Exit For
            End If
        End If
    Next i
    
    Endpos = LastNumPos - startpos
    
    Debug.Print Mid(Data, startpos, Endpos)
    

    结束子

    现在应该可以了。但如果文本包含“MD”后跟“WP”,那么它将只从 WP 获取代码。

    例如: data= "A850085_WPC-MD-01003_SRI 第 2 阶段 - 项目经理 - Dionysios Psachoulias"

    那么结果将是 结果=“WPC-MD-01003”

    【讨论】:

    • #prabu k,尝试使用第 6 行的代码(图像示例)结果是:MDC-WP-01003_SRI
    • 感谢您的支持 - 它工作得非常好,我可以在即时窗口中看到结果。但是,很抱歉,因为这可能是一个非常“简单”的问题,我如何将此代码转换为(UDF)公共函数,因为我使用的常用方法似乎不起作用并且返回“值”。
    • 我已经发布了函数作为另一个答案,看看告诉我。
    【解决方案3】:

    尝试类似的方法:-

    Dim cell
    Dim tmp as string
    
    For each cell in activesheet.columns(1).usedrange.cells
        If InStr(1, cell.Value, "_MDC_", vbTextCompare) > 0 Then
            tmp = Right(cell.Value, Len(cell.Value) - InStr(1, cell.Value, "_MDC_", vbTextCompare))
            tmp = Left(tmp, InStr(1, tmp, " ", vbTextCompare) - 1)
            cell.offset(0,2).value = tmp
        End If
    next cell
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多