CareTaker22
CareTaker22

Reputation: 1300

Retrieving digits from a string with a certain pattern

I have a string value of:

"Drop 1.0.2.34 - Compatible with core revision 123456"

And I am trying to get the value 1.0.2.34 with the full stops from the string. I am using Regex to try and get it, but it returns with a "" value.

Ex.

Match match = Regex.Match(string, "([0-9]*[.][0-9]*)*");
if (match.Success)
{
    string version = match.Captures[0].Value;
}

I think there is something small that I am missing because it does find a match in the string, but it doesn't have a value. Can someone please help?

Upvotes: 1

Views: 48

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Your regex matches an empty string, and since you are only looking for 1 match, it returns the empty string beofre the first char.

Use

[0-9]+(?:\.[0-9]+)+

See the regex demo

Details:

  • [0-9]+ - 1+ digits
  • (?:\.[0-9]+)+ - 1+ sequences of:
    • \. - a dot
    • [0-9]+ - 1+ digits.

C#:

string version = string.Empty;
Match match = Regex.Match(string, @"[0-9]+(?:\.[0-9]+)+");
if (match.Success)
{
    version = match.Value;
}

Upvotes: 4

Related Questions