检查AlphaNumeric字的字符串并使用VB转换为大写

时间:2015-06-27 00:11:43

标签: excel-vba vba excel

我正在讨论如何识别字符串中的字母数字单词,提取单词,转换为大写,然后将单词替换回字符串。

实施例: Free Standing Oven or90sdbgfx2 Brushed Stainless Steel

将转换为: Free Standing Oven OR90SDBGFX2 Brushed Stainless Steel

单词location可以是字符串中的任何位置,字符串中可能有多个字母数字。

2 个答案:

答案 0 :(得分:0)

这应该可以解决您的问题 -

Sub Main()
    Dim longString, result As String
    Dim arrayString() As String
    Set objRegExp_1 = CreateObject("vbscript.regexp")
    objRegExp_1.Pattern = "((?:[a-z][a-z]*[0-9]+[a-z0-9]*))" 'REGEX for alphanumeric words in the string
    longString = "Free Standing Oven or90sdbgfx2 Brushed Stainless Steel"
    arrayString = Split(longString, " ") 'Splits the string into an array of words so that each one can be matched with the REGEX pattern to check if its alphanumeric
    For i = 0 To UBound(arrayString)
        Set regExp_Matches = objRegExp_1.Execute(arrayString(i))
        If regExp_Matches.Count = 1 Then
            arrayString(i) = UCase(arrayString(i)) 'If a pattern match is found, the corresponding string is converted to uppercase and stored back
        End If
    Next
    result = Join(arrayString, " ") 'Combines elements of the modified array of words into a single string
    MsgBox (result)
End Sub

<强>输入

Free Standing Oven or90sdbgfx2 Brushed Stainless Steel

<强>输出

Free Standing Oven OR90SDBGFX2 Brushed Stainless Steel

答案 1 :(得分:0)

我无法说出所使用的正则表达式(归功于@CRAKC)。这是VBA的实现:

Sub VBASample()
    Dim tokens() As String
    Dim regex As RegExp
    Dim idx As Integer

    tokens = Split("Free Standing Oven or90sdbgfx2 Brushed Stainless Steel", " ")

    Set regex = New RegExp
    With regex
        .Pattern = "((?:[a-z][a-z]*[0-9]+[a-z0-9]*))"
        For idx = 0 To UBound(tokens)
            If .Test(tokens(idx)) Then
                tokens(idx) = UCase$(tokens(idx))
            End If
        Next idx
    End With

    Debug.Print Join$(tokens, " ")
End Sub

您需要引用Microsoft VBScript Regular Expressions 5.5。

相关问题