简体   繁体   中英

VBA parse string into tokens

I've got a string with a bunch of multi-letter codes in it and I'd like to parse it out according to those codes. I'm not sure how to make it look at more than one character to determine if it forms part of a code.

My string looks like this:

BBCTEEBOBBB

and I want to parse out these instances:

E BB CT BOB

So the result should be output (or an array) that looks like this:

BB CT EE BOB BB

I would use regular expressions. In Tools | References , add the highest version of the Microsoft VBScript Regular Expressions library available on your PC (5.5 on mine). Then you can use code such as the following:

Sub main()
  Dim x, m
  Set x = myparser("BBCTEEBOBBB")
  For Each m In x
    Debug.Print m.Value
  Next
End Sub

Function myparser(string_to_parse)
  Dim splitter As New RegExp
  splitter.Pattern = "E|BB|CT|BOB"
  splitter.Global = True
  Set myparser = splitter.Execute(string_to_parse)
End Function

The myparser function generates a MatchCollection object which can be toured as in the main subroutine. The output is a list, in order, of all of the matches found in the input string. You should be able to easily convert this to generate an array or space-delimited string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM