我尝试在Regex
中使用VBA
来匹配包含连字符和数字的整个单词。我知道\b
不起作用,因为它只设置了字母边界。
可以在Regex
的{{1}}中完成吗?
VBA
编辑:如果我不够清楚,我很抱歉。我的模式具有以下格式" AA2-11"。我想匹配整个字符串,这就是为什么我不能使用rx.pattern =" [az] [az] [0-9] - [0-9] [0-9]&# 34;因为如果你有例如" AA2-11-4"那会打到一场比赛,而我只是想要" AA2-11"
答案 0 :(得分:3)
这是你想要的吗?
更多关注
感谢您更新答案,但我担心它不起作用。假设我的文档有例如AA12-12,AB14-26。第一次出现不匹配。
Sub Sample()
Dim regString As String
Dim myRegExp As RegExp
regString = "AA12-12#AB14-26" '<~~ Matches
'regString = "#AA12-12,AB14-26#" '<~~ Matches
'regString = "AA2-11 is a sample string" '<~~ Matches
'regString = "This is a sample AA2-11-11" '<~~ Doesn't Match
'regString = "This is a sample AA2-11-11 string" '<~~ Doesn't Match
'regString = "This is a sample AA2-11-11 string" '<~~ Doesn't Match
regString = " " & regString & " "
Set myRegExp = New RegExp
With myRegExp
.Global = True
.Pattern = "\b[a-zA-Z]{2}\d{1,}-\d{2,}\b(?=[^-])"
If myRegExp.Test(regString) Then
Debug.Print "Found"
Else
Debug.Print "Not Found"
End If
End With
End Sub
或者像这样
Sub Sample()
Dim regString As String
Dim myRegExp As RegExp
Dim myMatches As MatchCollection
Dim myMatch As Match
regString = "AA12-12,AB14-26" '<~~ Matches
'regString = "#AA12-12,AB14-26#" '<~~ Matches
'regString = "AA2-11 is a sample string" '<~~ Matches
'regString = "This is a sample AA2-11-11" '<~~ Doesn't Match
'regString = "This is a sample AA2-11-11 string" '<~~ Doesn't Match
'regString = "This is a sample AA2-11-11 string" '<~~ Doesn't Match
regString = " " & regString & " "
Set myRegExp = New RegExp
With myRegExp
.Global = True
.Pattern = "\b[a-zA-Z]{2}\d{1,}-\d{2,}\b(?=[^-])"
Set myMatches = myRegExp.Execute(regString)
For Each myMatch In myMatches
Debug.Print myMatch.Value
Next
End With
End Sub