我的字符串是这样的文件名:
示例文本(A12 V1.1)
示例(V2)文本(A9 V2.3 8.99)
样本超文本(A34 8.3 V4)
如何仅提取以括号开头但不包含“ V”的字符串?
即-1.1、2.3、4
答案 0 :(得分:0)
尝试此UDF
Function ExtractByRegex(sTxt As String)
With CreateObject("VBScript.RegExp")
.Pattern = "V\d+(.)?(\d+)?"
If .Test(sTxt) Then ExtractByRegex = .Execute(sTxt)(0).Value
End With
End Function
这是另一个版本,您可以在其中格式化输出
Sub Test_ExtractByRegex_UDF()
MsgBox ExtractByRegex("A9 V2.3 8.99")
End Sub
Function ExtractByRegex(sTxt As String)
With CreateObject("VBScript.RegExp")
.Pattern = "V\d+(.)?(\d+)?"
If .Test(sTxt) Then sTxt = Replace(.Execute(sTxt)(0).Value, "V", "")
If Not InStr(sTxt, ".") Then sTxt = sTxt & "." & "000"
ExtractByRegex = Split(sTxt, ".")(0) & IIf(InStr(sTxt, "."), ".", "") & Format(Split(sTxt, ".")(1), "000")
End With
End Function
答案 1 :(得分:0)
VBA的字符串函数可以复制静态模式的结果,并且如果您要删除 V 前缀,则可能需要返回一个真数字。
Option Explicit
Function ExtractWithoutRegex(sTxt As String)
Dim b As Long, v As Long
b = InStrRev(sTxt, "(")
v = InStr(b, sTxt, "V")
ExtractWithoutRegex = vbNullString
If v > b Then
sTxt = Mid$(sTxt, v + 1)
sTxt = Split(sTxt)(0)
ExtractWithoutRegex = Val(sTxt)
End If
End Function