【问题标题】:MS Word RegEx capitalizing letters after a special characterMS Word RegEx 在特殊字符后大写字母
【发布时间】:2013-11-30 23:45:41
【问题描述】:

我正在尝试为 MS Word 2010 编写一个 VBA 宏,在特殊字符后将字母大写。在我的情况下,一个下划线“_”。我要修改的单词以特殊前缀开头。我在更换操作时遇到问题。我正在使用 Microsoft 正则表达式库 5.5。

这是我目前所拥有的:

Sub ReplaceFunc()
'
' ReplaceFunc Macro
'
'
    Debug.Print ("entered replaceFunc")

    Dim myRegex As New RegExp
    myRegex.Global = True
    myRegex.IgnoreCase = False
    myRegex.MultiLine = True

'   i want to find all words in the document which start with BlaBlub and have a suffix like _foo_bar or _foo_bar_foo
'   e.g. BlaBlub_foo_bar, BlaBlub_foo_foo_bar_bar, BlaBlub_foo_bar_foo    
    myRegex.Pattern = "\bBlaBlub(_([a-z])+)+\b"

'   works i get the results i was looking for    
    Set Matches = myRegex.Execute(ActiveDocument.Range.Text)

'   now i want to capitalize every letter after a "_", e.g. BlaBlub_foo_bar --> BlaBlub_Foo_Bar    
    For Each Match In Matches
'   The idea is to run a new RegEx on every found substring but this time with replace
        Dim mySubRegex As New RegExp
        mySubRegex.Global = True
        mySubRegex.IgnoreCase = False
        mySubRegex.MultiLine = True
'   Matching every underscore followed by a non capital letter        
        mySubRegex.Pattern = "_([a-z])"

'   getting start and endindex from the match to run the regex only on the found word
        startIndex = Match.FirstIndex
        endIndex = (Match.FirstIndex + Match.Length)

'   where it fails with a syntax error        
        mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")

    Next

    Debug.Print ("leaving replaceFunc")


End Sub

VBA 宏失败,行中出现语法错误:

mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")

我没有想法,该怎么做才能让它发挥作用。你能指出我的错误是什么以及如何解决它吗?

【问题讨论】:

    标签: regex vba ms-word


    【解决方案1】:

    这很容易纠正,只需去掉括号:

    mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")
    

    =>

    mySubRegex.Replace ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1"
    

    或者

    Dim varVal
    varVal = mySubRegex.Replace(ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text , "_\u$1")
    

    【讨论】:

    • 嗯,这是有道理的。但这似乎不是脚本中唯一的问题。 startIndex 没有指向我期望的位置。如果我做 Debug.Print (ActiveDocument.Range(Start:=startIndex, End:=endIndex).Text) 我不会得到与 Debug.Print (Match.Value) 相同的 als。这怎么可能?
    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多