VBA 正则表达式替换循环 [英] VBA Regex Replace Loop
问题描述
目前在用于票务系统格式化的正则表达式替换循环方面存在问题
Currently having issues with a regex replace loop for ticketing system formatting
我正在测试一段代码,它将正则表达式匹配票号的特定格式.票号格式为INC01234567"(最多8位数字).INC"可以是可选的,这样用户只需输入结束编号(IE 1234567),循环将添加额外的0"以提供最多 8 位的数字.然而,目前,我被困在一个数学逻辑问题上,如果您输入完整的票号,它会在结果中添加一个太多的 0.
I am testing a segment of code that will regex match a specific format for a ticket number. The ticket number should be in a format of "INC01234567" (up to 8 numeric digits). The "INC" can be optional so that the user can just type in the ending number (IE 1234567) and the loop will add the additional "0's" to give the numeric amount up to 8 digits. Currently, however, I am stuck on a math logic issue where it is adding one too many 0's to the result if you type in a full ticket number.
我
Sub Incident()
Dim sInc As String 'Incident Number Field
Dim strPattern As String: strPattern = "^(?:INC|NC|C)?([0-9]{1,8}$)"
Dim strReplaceINC As String: strReplaceINC = "$1"
Dim regEx As New RegExp
Dim strInput As String
Dim IncResult As Boolean
Do
If strPattern <> "" Then
strInput = inputbox("Input Incident Number", "Ticket Number")
If strInput = vbNullString Then
Exit Sub
End If
IncResult = False
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
sInc = regEx.Replace(strInput, strReplaceINC)
Dim L As Integer: L = Len(sInc)
Do
sInc = "0" & sInc
L = L + 1
Loop While L <= 8
sInc = "INC" & sInc
IncResult = True
'sInc = strInput
Else
MsgBox ("Please input a valid ticket number format")
IncResult = False
End If
End If
Loop While IncResult = False
MsgBox (sInc)
End Sub
推荐答案
循环是不必要的开销,直接使用Format()
The loop is unnecessary overhead, just use Format()
替换所有这些:
Dim L As Integer: L = Len(sInc)
Do
sInc = "0" & sInc
L = L + 1
Loop While L <= 8
sInc = "INC" & sInc
有了这个:
sInc = "INC" & Format(sInc, "00000000")
这篇关于VBA 正则表达式替换循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!