使用REGEX进行案例转换

时间:2018-01-17 19:56:13

标签: regex excel vba excel-vba

在VBA中使用Excel和REGEX,我是新手。

我需要通过strReplace命令将一个捕获组的内容从全部大写转换为标题。我不能对strReplace的结果使用Excel PROPER函数,因为它不能提供所需的结果。

样本单元格内容是(并非所有单元格都是这样的,这就是为什么字符串模式定义更具包容性):

FDI850-4224 JIM SMITH 29 HP (21.6 kw)

我的字符串模式是:

strPattern = "^(\D{2,4}\d{0,4})-(\d{1,4}) (.*)\s(\d\d)( HP)\s\((\d\d.\d)\skw\)"

我的替换模式是:

strReplace = "$1-$2 - Juniper $1 Part, $3, $4HP, $6KW"

放置在相邻单元格中的当前结果是:

FDI850-4224 - Juniper FDI850 Part, JIM SMITH, 29HP, 21.6KW

我想要放置在相邻单元格中的结果是:

FDI850-4224 - Juniper FDI850 Part, Jim Smith, 29HP, 21.6KW

我可以在strReplace中使用捕获组3(。*)将其从全部大写更改为标题吗?

这是我的VBA代码:

Function tom_test(Myrange As Range) As String

Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String

strPattern = "^(\D{2,4}\d{0,4})-(\d{1,4}) (.*)\s(\d\d)( HP) \((\d\d.\d\d)\skW\)"

If strPattern <> "" Then
    strInput = Myrange.Value
    strReplace = "$1-$2 - Juniper $1 Part, $3, $4HP, $6KW"
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        tom_test = regEx.Replace(strInput, strReplace)

    Else
        tom_test = "No Bueno"
    End If
End If    
End Function

我尝试了从REGEX函数获取结果然后在其上使用Excel PROPER函数的两步过程,但它弄乱了其他捕获组结果的结果: 以下是对strReplace的结果使用PROPER后发生的事情:

Fdi850-4224 - Juniper Fdi850 Part, Jim Smith, 29Hp, 21.6Kw

我将不胜感激。

1 个答案:

答案 0 :(得分:3)

试试这个:

Option Explicit
Function tom_test(Myrange As Range) As String

Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String

Dim MC As MatchCollection

strPattern = "^(\D{2,4}\d{0,4})-(\d{1,4}) (.*)\s(\d\d)( HP)\s\((\d\d.\d)\skw\)"

If strPattern <> "" Then
    strInput = Myrange.Value
    strReplace = "$1-$2 - Juniper $1 Part, $3, $4HP, $6KW"
    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        Set MC = regEx.Execute(strInput)

        strReplace = Replace(strReplace, "$3", StrConv(MC(0).SubMatches(2), vbProperCase))

        tom_test = regEx.Replace(strInput, strReplace)

    Else
        tom_test = "No Bueno"
    End If
End If
End Function