【问题标题】:Regular Expression error using Visual Basic for Applications使用 Visual Basic for Applications 的正则表达式错误
【发布时间】:2015-02-21 20:23:06
【问题描述】:

使用http://www.regexr.com/ 模式进行测试\"([\s\S]*?)\" 可以匹配我的目标字符串。但是,在我的代码中,我得到一个类型不匹配并且不知道为什么,IDE 改变了字符串在引号内的格式

Dim Matches
Dim objectRegularExp As RegExp

If Application.FileDialog(msoFileDialogOpen).Show <> -1 Then Exit Sub
FileName = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Open FileName For Input As #1
yourText = Input(LOF(1), #1)
Close #1
LengthOfFile = Len(yourText)

'create regular expression

Set objectRegularExp = New RegExp
With objectRegularExp
     .Pattern = "" \ "(\s\S*?)\"""                 <type mismatch runtime error
     .Global = True
     .MultiLine = True
End With
Set Matches = objectRegularExp.Execute(yourText)

【问题讨论】:

    标签: regex excel vba basic


    【解决方案1】:

    你的引用是错误的。

    字符串用引号括起来。要将引号括在字符串中,您需要 2 个引号。你的字符串开头有两个引号(所以是一个空字符串)你的字符串中间有一个单引号。如果它首先是有效的,则终止该字符串。

    通常我们像这样使用非懒惰的方式

    .Pattern = Chr(34) & " \ " & Chr(34) & "(\s\S*?)\" & chr(34)

    【讨论】:

    • 这是行之有效的模式 我从未想过使用 Chr(34)。我将阅读双引号 .Pattern = Chr(34) & "(\s\S*?)" & Chr(34) 的使用。谢谢@mfitzp
    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多