How Can I Extract a Series of Characters Found in the Middle of a String?
Hey, Scripting Guy! I have a series of strings that look something like this: xxxxyyyyyyxx. How can I extract just the y’s?
Hey, JB. And, yes, it is a Friday. But, hey, it’s just a coincidence that we happened to pick an easy question on a Friday, the day we’re itching to get out of here and go home and spend the weekend watching football and basketball. Besides, we feel it’s important to tackle these easier questions from time-to-time to better help those readers who are new to scripting.
Boy, that’s so convincing we almost believe it ourselves.
But enough about us. Let’s talk about the code instead:
strPhrase = “xxxxyyyyyyxx” strExtract = Mid(strPhrase, 5, 6) Wscript.Echo strExtract
As you can see, there’s not much to this script. We start out by assigning the string xxxxyyyyyyxx to a variable named strPhrase. As you noted, there’s a pattern to your series of strings: each string starts out with four characters we don’t care about, followed by six characters we do care about, followed by two other characters we don’t care about. Our job is simple: grab those six characters out of the middle of the string.
So how do we do that? We do that by using the Mid function:
strExtract = Mid(strPhrase, 5, 6)
As you can see, we pass the Mid function three parameters:
strPhrase. This is the string we want to parse.
5. This is the character position we want to start grabbing characters from. We want to start with character 5 (skipping the first 4 characters), so we pass 5 as the second parameter.
6. The number of characters we want to grab.
In other words, starting with character 5, we want to grab 6 characters out of the middle of the string and store them in a variable named strExtract. And what happens when we echo back the value of strExtract? Why, we get this, of course:
Keep in mind that we’re dealing solely with numbers here; we’re not looking for the actual string yyyyyy. With that in mind, consider this script:
strPhrase = “abcdcreateef” strExtract = Mid(strPhrase, 5, 6) Wscript.Echo strExtract
strPhrase = “ghijdeletekl” strExtract = Mid(strPhrase, 5, 6) Wscript.Echo strExtract
Here’s what we get when we run this script:
Again, we started at character 5, and grabbed a total of 6 characters. Simple, huh?
And so it’s Friday and we’ve already finished the Hey, Scripting Guy! column. Gee, what do you think we should do now …?