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"
ASP.NETVisual Basic.NET.NET Programming

Avatar of undefined
Last Comment
Bill Prew

8/22/2022 - Mon
it_saige

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 -Capture.PNG-saige-
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
it_saige

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Bill Prew

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
maqskywalker

ASKER
thanks. Both great examples!
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Bill Prew

Welcome, glad that was useful.


»bp