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

Need a function to take a string, and return numbers in that string

The function will be passed

ie

thepath + picnum1256.jpg
 and so on

needs to return:
1256
help!

0
pdidow
Asked:
pdidow
  • 2
1 Solution
 
tomvergoteCommented:
what language do you want that in?
0
 
pdidowAuthor Commented:
VB.NET
0
 
pratap_rCommented:
simple... use regex

        Dim r As New System.Text.RegularExpressions.Regex("[^0-9]*") '<-- one liner
        MsgBox(r.Replace("thepath + picnum1256.jpg", "")) 'example 1.will display 1256
        MsgBox(r.Replace("Hello..123,4+5~6&7*8(9)0", "")) 'example 2. will display 1234567890


Have Fun!
Pratap
0
 
pratap_rCommented:
mm just to explain what i did

        Dim r As New System.Text.RegularExpressions.Regex("[^0-9]*") '<-- one liner

declaring a new object of type Regex with [^0-9]* as pattern. Meaning match all characters which are not in the range 0-9, effectively any non numerals.

        MsgBox(r.Replace("thepath + picnum1256.jpg", "")) 'example 1.will display 1256

the r.Replace i used here takes two parameters, the string to search for and the string to replace the match with. The regex engine applies the pattern given to it in the constructor and for each match it substitutes the replacement string (the second parameter).

        MsgBox(r.Replace("Hello..123,4+5~6&7*8(9)0", "")) 'example 2. will display 1234567890

This line is just to show how the filtering works.

putting this in a function....

    Function GetNumber(ByVal s As String) As String
        Dim r As New System.Text.RegularExpressions.Regex("[^0-9]*")
        GetNumber = r.Replace(s, "")
    End Function

and your calls will be
        MsgBox(GetNumber("Hello..123,4+5~6&7*8(9)0")) 'will display 1234567890
        MsgBox(GetNumber("thepath + picnum1256.jpg")) 'will display 1256


Have Fun!
Pratap
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

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