Split and Get Number from string using Regular Expression in C# and VB.Net

Last Reply 6 months ago By dharmendr

Posted 6 months ago

Hi! I used below code, but has some error. 

string selected = "";
string value = "Part 1 for example∞5 Part 2 for practice∞3";
string selectedValues = value;
foreach (string item in selectedValues.Split('∞'))
{
    string number = System.Text.RegularExpressions.Regex.Match(item, @"\d+").Value;
    if (!string.IsNullOrEmpty(number.TrimStart(' ')))
    {
        selected += number + ",";
    }
}

Output result must be 5,3

Now its result 1,5,3 its wrong

You are viewing reply posted by: dharmendr 6 months ago.
Posted 6 months ago

Hi PRA,

Refer below code.

C#

string selected = "";
string value = "Part 1 for example∞5 Part 2 for practice∞3";
string selectedValues = value;
for (int i = 1; i < selectedValues.Split('∞').Length; i++)
{
    string number = System.Text.RegularExpressions.Regex.Match(selectedValues.Split('∞')[i], @"\d+").Value;
    if (!string.IsNullOrEmpty(number.TrimStart(' ')))
    {
        selected += number + ",";
    }
}

VB.Net

Dim selected As String = ""
Dim value As String = "Part 1 for example∞5 Part 2 for practice∞3"
Dim selectedValues As String = value

For i As Integer = 1 To selectedValues.Split("∞"c).Length - 1
Dim number As String = System.Text.RegularExpressions.Regex.Match(selectedValues.Split("∞"c)(i), "\d+").Value
    If Not String.IsNullOrEmpty(number.TrimStart(" "c)) Then
        selected += number & ","
    End If
Next