• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

How do I Convert a String to an Integer when the string is prefixed with a character(s)

Hi,

I am trying to do the above, i.e.

   "ABC123"   -->  123
   "X12"    -->  12

Any ideas???

Thanks

James
0
James Atkin
Asked:
James Atkin
  • 3
  • 2
1 Solution
 
Dave BrettCommented:
Hi jatkin,

You could use a RegExp such as

Sub GetDigits()
    Dim Mystr As String, RegEx As Object
    Set RegEx = CreateObject("vbscript.regexp")
    Mystr = "ABC123" & vbNewLine & "X12"
    RegEx.Pattern = "[\d+]"
    RegEx.Global = True
    MsgBox RegEx.Replace(Mystr, "")
End Sub

Cheers

Dave
0
 
James AtkinSenior Principle Software EngineerAuthor Commented:
Interesting solution...

The example code appears to return the part I need to throw away ;-)  i.e.  
   ABC
   X

Haven't dealt with Regular Expressions since the days of Lexx & Yacc...
What is the 'inverse' of [\d+]?

James
0
 
Dave BrettCommented:
I'm a dope....left out the negating character

RegEx.Pattern = "[^\d+]"

Cheers

Dave
0
 
James AtkinSenior Principle Software EngineerAuthor Commented:
That's the one!

Thanks for the help....

James
0
 
Dave BrettCommented:
Thanks for the grade James  :)

The RegEx I gave is a global one so it will convert an entire string
If you had a string such as
"ABC123 X12"
and you only wanted to pull out the first group of non numbers then remove the line
RegEx.Global = True

and I should have written the pattern as
"[^\d]+"

Cheers

Dave
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now