使用RegExp仅保留字符串中的大写字母

时间:2018-03-22 17:11:18

标签: regex vba

我有一列字符串,我想从中提取大写单词,然后在另一列中提取。单词总是在字符串的开头。例如:

APPLE ORANGE_20 lbs_15 ------> APPLE ORANGE

BANANA_10 lbs_30 ----------------->香蕉

GRAPE MANGO 30lbs_o ----------> GRAPE MANGO

这是我到目前为止所做的,但我很难设置模式以获得所需的输出:

Sub ExtractUPPERCASE()


Dim re As Object, mc As Object
Dim r As Range, c As Range
Dim s As String
Dim wbdata As Workbook
Dim wsData As Worksheet
Set wbdata = Workbooks("trial1")
Set wsData = wbdata.Worksheets("Final Data")

wsData.Activate
Set r = wsData.Range("D1", Cells(Rows.Count, "D").End(xlUp))
Set re = CreateObject("vbscript.regexp")
With re
    .Global = True
    .ignorecase = False
    .MultiLine = True
    .Pattern = "^\s*([A-Z\W]+\b)\W+([\w\s]+)"
   '.Pattern = "([^a-z]+|[^0-9]+|(?=.*[^\w_]))" I tried this pattern but it didn't get what i want 
End With

For Each c In r
    s = c.Text
    If re.test(s) = True Then
        Set mc = re.Execute(s)
            c(1, 13) = mc(0).submatches(0)
    End If
Next c

Range(r(1, 13), r(1, 13)).EntireColumn.AutoFit

End Sub

感谢您的时间:)

1 个答案:

答案 0 :(得分:0)

试试这个:

Sub ExtractUPPERCASE()


Dim re As Object, mc As Object
Dim r As Range, c As Range
Dim s As String
Dim wbdata As Workbook
Dim wsData As Worksheet
Set wbdata = Workbooks("trial1")
Set wsData = wbdata.Worksheets("Final Data")

wsData.Activate
Set r = ActiveSheet.Range("A1", Cells(Rows.Count, "A").End(xlUp))
Set re = CreateObject("vbscript.regexp")
With re
    .Global = True
    .ignorecase = False
    .MultiLine = True
    .Pattern = "[A-Z]+\s?[A-Z]+"
End With

For Each c In r
    s = c.Text
    If re.test(s) = True Then
        Set mc = re.Execute(s)
            c(1, 13) = mc.Item(0).Value
    End If
Next c

Range(r(1, 13), r(1, 13)).EntireColumn.AutoFit

End Sub