【发布时间】:2019-02-28 04:21:33
【问题描述】:
我遇到了用于票务系统格式的正则表达式替换循环问题。
我正在测试一段代码,它将正则表达式匹配票号的特定格式。票号的格式应为“INC01234567”(最多 8 位数字)。 “INC”可以是可选的,这样用户只需输入结束数字(即 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
【问题讨论】:
-
基于您的代码,由于您的“Do While”循环,您总是在结果中插入一个“0”,对吗?如果是这样,为什么不使用 For 循环,条件是结果少于 8 个字符?
-
总是以
INC开头吗?