K V
K V

Reputation: 578

Regex Match multiple occurences with numbers in string C#

I've been searching for my problem answer, but couldn't find so I write here.

I want to take a string example: = "37513220102304920105590"

and find all matches for numbers of length 11 which starts 3 or 4.

I have been trying to do so:

string input = "37513220102304920105590"
var regex = new Regex("^[3-4][0-9]{10}$");
var matches = regex.Matches(trxPurpose);

// I expect it to have 3 occurances "37513220102", "32201023049" and "30492010559"
// But my matches are empty. 
foreach (Match match in matches)
{
    var number = match.Value;

    // do stuff
}

My question is: Is my regex bad or I do something wrong with mathing?

Upvotes: 1

Views: 144

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

Use capturing inside a positive lookahead, and you need to remove anchors, too. Note the - between 3 and 4 is redundant.

(?=([34][0-9]{10}))

See the regex demo.

In C#, since the values are captured, you need to collect .Groups[1].Value contents, see C# code:

var s = "37513220102304920105590";
var result = Regex.Matches(s, @"(?=([34][0-9]{10}))")
        .Cast<Match>()
        .Select(m => m.Groups[1].Value)
        .ToList();

Upvotes: 3

Related Questions