Drag and Drop
Drag and Drop

Reputation: 2734

match a pattern multiple time with a separator

In order to make an code cleaner i want to match multiple time my partern in a string with ; as separator.
For now I split on ; like this.

string[] argD = _input.Split(';');

So the actual regex work fine. But I want to see if I can eliminate that Split.

Input:

1d2;1d6

and

1d2

Patern: /gmi

This pattern is giving me match for 1d2

^(\d+)d(\d+)?$

For now I am splitting on ; then I apply the regexp

Expected result:

[ [ 1 , 2 ] , [  1, 6 ] ]

[ [ 1 , 2 ] ] 

MCVE: C# Code

int cpt = 0;
string uni = "1d2";
string multi = "1d2;1d8";

MatchCollection RegexMatchUni = Regex.Matches(uni, @"^(\d+)d(\d+)?$");
MatchCollection RegexMatchMulti = Regex.Matches(multi, @"^(\d+)d(\d+)?$");

Console.WriteLine("<TEST UNI>");
foreach (Match m in RegexMatchUni){
    cpt++;
    Console.WriteLine("{0}: {1}d{2}"
                        , cpt
                        , m.Groups[1].Value
                        , m.Groups[2].Value);
    var temp = m.Groups[1].Value;
}

Console.WriteLine("\n<TEST MULTI>");
cpt = 0;
foreach (Match m in RegexMatchMulti){
    cpt++;
    Console.WriteLine("{0}: {1}d{2}"
                        , cpt
                        , m.Groups[1].Value
                        , m.Groups[2].Value);
}

Upvotes: 0

Views: 788

Answers (1)

dotNET
dotNET

Reputation: 35400

Remove the ^ and $ characters from your multi regexp and it will start working. These characters force the regular expression to match the entire string only, not as a substring.

Upvotes: 2

Related Questions