当前在售票系统格式化的正则表达式替换循环方面存在问题
我正在测试一段代码,该代码段将使正则表达式与票号的特定格式匹配。票号应采用“ INC01234567”的格式(最多8个数字)。 “ INC”可以是可选的,以便用户只需键入结尾数字(IE 1234567),循环将添加附加的“ 0”以使数字量最多为8位数字。但是,目前,我陷入了数学逻辑问题,如果您输入完整的票证号码,它将在结果中添加太多0。
我
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
答案 0 :(得分:2)
循环是不必要的开销,只需使用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")
答案 1 :(得分:0)
您要在循环结束时检查条件,这意味着无论sInc的长度如何,循环将至少运行一次。
只需替换:
Do
sInc = "0" & sInc
L = L + 1
Loop While L <= 8
使用:
While L < 8
sInc = "0" & sInc
L = L + 1
Wend
答案 2 :(得分:0)
正则表达式"^(?:INC|NC|C)?([0-9]{1,8}$)"
与8位数字的票证号码012345678匹配,不是吗?因此If regEx.Test(strInput) Then
是正确的,并且do..loop
至少在中断之前准时运行