Eni
Eni

Reputation: 125

Regex to get numbers after a period in a string

I'm trying to find the right regex to extract the numbers after the . in the string below. E.g, the first line should return and array of 1 1 1 1 1, the second should return 2 1 0 1 2. I can't seem to figure the correct regex expression to achieve this. Any help would be appreciated.

line = 0.1, 1.1, 2.1, 3.1, 4.1            // payline 0
line = 0.2, 1.1, 2.0, 3.1, 4.2            // payline 1

So far, I have the code below, but it just returns all the the numbers in the sting instead. eg, the first line returns 0 1 1 1 2 1 3 1 4 1 0 and the second returns 0 2 1 1 2 0 3 1 4 2 1

foreach (var line in Paylines)
{
    int[] lines = (from Match m in Regex.Matches(line.ToString(), @"\d+")
                                     select int.Parse(m.Value)).ToArray();

    foreach (var x in lines)
    {
        Console.WriteLine(x.ToString());        
    }
}

Upvotes: 1

Views: 2031

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626853

You may use a lookbehind-based regex solution:

@"(?<=\.)\d+"

It matches 1+ digits after a dot without placing the dot into a match value.

See the regex demo.

In C#, you may use

var myVals = Regex.Matches(line, @"(?<=\.)\d+", RegexOptions.ECMAScript)
        .Cast<Match>()
        .Select(m => int.Parse(m.Value))
        .ToList();

See the C# demo.

The RegexOptions.ECMAScript option is passed for the \d to only match ASCII digits in the [0-9] range and avoid matching other Unicode digits.

Upvotes: 5

Related Questions