regex - 使用 REGEX 进行大小写转换

标签 regex vba excel

在 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

我将不胜感激任何帮助。

最佳答案

尝试这个:

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

关于regex - 使用 REGEX 进行大小写转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48309014/

相关文章:

visual-c++ - 加载 VBA 时以编程方式重建 .exd 文件

vba - 使用 VBA 在 Word 中设置嵌套字段

regex - .htaccess 没有查询参数的重定向

ruby 正则表达式挂起

excel - 从 Excel VBA 运行 Bat 文件

excel - 编辑多个工作簿的公式以删除外部引用/更改对本地工作簿的引用

vba - VBA 中的 With block 中有超过 1 个单元格范围

javascript - 正则表达式不匹配序列中的两个相同字符

java - 如何使用正则表达式替换字符串

vba - <Excel-VBA> "Type mismatch"将值从单元格复制到文本框时出错