Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

extract numbers [0-50] from a string -- use regex?

Status
Not open for further replies.

jpeyer

Technical User
Sep 12, 2002
8
US
I need a way to extract a number (will be up to two-digit) from a string... I will have no problem converting that resulting string to an integer, but just initially getting the number out of the string...

the string may look like any of these:
'blahblahblah1.asp', 'blahblahblah1_submit.asp', 'blahblahblah12.asp' or 'blahblahblah12_submit.asp'

It'd be rather easy to create four checks for the string to go through every time to check absolute positions (and if 'Cint(string)=true' then we have a winner), but there has got to be an easier, more efficient way to get that number out of the string using regular expressions... correct? ...or perhaps I'm on crack.

Any help would be greatly appreciated.

Jeremy



 
Sure, regexp would be great for this.
Basically we will want to set up a regex object:
Code:
Dim regExpObj
Set regExpObj = New RegExp
regExpObj.Global = true

Than we need to specify a pattern (there is an extremely good FAQ in the Java forum on patterns and such for RegExpressions)
Code:
regExpObj.pattern = "\d{1,2}"   'one to two numbers in a row

Then we want to execute this against out string:
Code:
'pretend we have a string called myContent
Dim matches, match
Set matches = regExpObj.execute(myContent)

Then lets print out every match in the matches collection:
Code:
For each match in matches
   response.Write &quot;A match! --&gt; &quot; & match & &quot;<br>&quot;
Next

And voila, numbers. Now I haven't tested the regular expression above, so it may not be greedy enough and making multiple matches off the same set of numbers, for example:
sjdghfgjs76skdgsh
might be making a match for 7, 6, and 76.

If you read through the FAQ mentioned above (I'll post a link in sec) I think you'll get a much better understanding for Regular expressions and how cool the really are.
While the FAQ was written for4 the Java forum, the actual regular expression patterns are nearly universal (i say nearly because if I don't someone will find an example somewhere of a bad implementation):
faq269-2689

Hope this helps,

-Tarwn
________________________________________________________________________________
Want to get great answers to your Tek-Tips questions? Have a look at faq333-2924
 
Excellent.

I guess my big problem was with the 'execute' command -- have THAT all sorted out now.

After a bit of fooling around with this, everything is working great(and yes, the pattern was greedy enough).

Thanks,

Jeremy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top