Link to home
Start Free TrialLog in
Avatar of maqskywalker
maqskywalker

asked on

parsing a string variable and get the numbers

I'm using visual basic .net in a aspx web forms application

If I have a string variable that looks like this that contains numbers and characters.

How do I save only the numbers in a different variable called Intvariable1 ?

Testvariable1 = "123|YYY"

sometimes the values in TestVariable1 will be this "123|YYY"  or this "12|YYY"  or this "3|YYY"
Avatar of it_saige
it_saige
Flag of United States of America image

If that is your value set, then I would split on the pipe and TryParse the splits as a numeric type; e.g. -
Module Module1
    Sub Main()
        Dim values = New String() {"123|YYY", "12|YYY", "3|YYY"}
        For Each value In values
            Dim result As Integer
            Dim selects = (From split In value.Split(New String() {"|"c}, StringSplitOptions.RemoveEmptyEntries)
                           Where Integer.TryParse(split, result)
                           Select split)
            For Each selected In selects
                Console.WriteLine($"{value} contains {selected}")
            Next
        Next
        Console.ReadLine()
    End Sub
End Module

Open in new window

Which produces the following output -User generated image-saige-
Avatar of maqskywalker
maqskywalker

ASKER

On this link
https://stackoverflow.com/questions/13356018/get-only-numbers-from-string

I saw this example:

resultString = Regex.Match(subjectString, @"\d+").Value;


if subjectstring = "28|NN"

then it returns 28

But it only works for positive numbers.

Because if subjectstring = "-1|NN"

then it returns 1

How do fix regex example to also work with negative numbers?
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks. Both great examples!
Welcome, glad that was useful.


»bp