Eugen
Eugen

Reputation: 2990

Extract group of number from text

Having such a text

Above includes - Add/Remove Member To/From Nested Group - 1.24.12 / 1.24.13

how do I create a regular expression that would return the 2 groups of 3 numbers I have. Expected result

1.24.12
1.24.13

I tried to use such an expression

private static Regex MRDNumbers = new Regex(@"((\d+.?){2,})+");

but it doesn't work as needed.

Also, the length of the group can be different, it can be

1.22
13.4.7
1.2.3.4
1.2.3.4.5
1.2.3.4.5.6

Upvotes: 2

Views: 57

Answers (5)

p.s.w.g
p.s.w.g

Reputation: 149020

The problem is the . in your pattern. In the regular expression language, the . character matches any character (except in single-line mode), so you have to escape it with a \ character to match just periods.

Try this instead:

private static Regex MRDNumbers = new Regex(@"((\d+\.?){2,})+");

To capture all the matched numbers in a list, you might try this:

private Regex MRDNumbers = new Regex(@"(\d+?)(?:\.(\d+))+");

string input = "Above includes - Add/Remove Member To/From Nested Group - 1.24.12 / 1.24.13";
MRDNumbers.Matches(input).Cast<Match>().Dump();
var list = 
    (from m in MRDNumbers.Matches(input).Cast<Match>()
     select 
     from g in m.Groups.Cast<Group>().Skip(1)
     from c in g.Captures.Cast<Capture>()
     select c.Value)
    .ToList(); 
// [ [ 1, 24, 12 ], [ 1, 24, 12 ] ]

Or in fluent syntax:

var list = 
    MRDNumbers.Matches(input).Cast<Match>()
              .Select(m => m.Groups.Cast<Group>()
                            .Skip(1)
                            .SelectMany(g => g.Captures.Cast<Capture>())
                            .Select(c => c.Value))
              .ToList();

Upvotes: 2

Eugen
Eugen

Reputation: 2990

ok, problem solved, I did use a wrong idea in C#. Here is the correct code

private static Regex MRDNumbers = new Regex(@"((\d+\.?){2,})+");
static void Main(string[] args)
{
    string s = " Above includes - Add/Remove Member To/From Nested Group - 1.24.12 / 1.24.13.45 45.78";
    MatchCollection m = MRDNumbers.Matches(s);

    foreach (Match match in m)
    {
        Debug.WriteLine(match.Value);
    }
}

Upvotes: 1

melwil
melwil

Reputation: 2553

You need to escape your dot and one of the groups. The reason you are getting out 1.24.12 12 is that 12 is the last match that fills group 2, so you get that spit out.

Try this one:

private static Regex MRDNumbers = new Regex(@"((?:\d+\.?){2,})+");

Upvotes: 0

Anirudha
Anirudha

Reputation: 32797

You can use this regex

\d+(\.\d+)+

You can get a list of such numbers with this code

List<String> lst=Regex.Matches(input,regex)
                      .Cast<Match>()
                      .Select(x=>x.Value);

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85046

Try escaping your .:

((\d+\.?){2,})+

Notice that . is now \.. Seems to be working in regexpal.

Upvotes: 0

Related Questions