1

I need to extract version information from the following string

993-756-V01 ver 02a

What regex I need to use in order to extract 01 and 02 from 993-756-V01 ver 02a

I tried to extract the version substring i.e. V01 ver 02a with the below regex.

[A-Z][0-9]{2} ver [0-9]{2}

But is there a more direct way to extract the information

5
  • 1
    V(\d+)\s*ver\s*(\d+) Commented Dec 7, 2016 at 10:08
  • 1
    I suggest adding groups: [A-Z](?<major>[0-9]{2}) ver (?<minor>[0-9]{2}) Commented Dec 7, 2016 at 10:09
  • @DmitryBychenko: How do I achieve grouping when it doesn't recognise the <major> and <minor> entries beforehand. Do you mean this way [A-Z]([0-9]{2}) ver ([0-9]{2}) Commented Dec 7, 2016 at 10:36
  • @this-Me: What do you mean by it doesn't recognise the <major> and <minor> entries beforehand? The regex matches and captures the necessary details into the "major" and "minor" groups. See Dmitry's regex demo. You may also use [A-Z](?<major>[0-9]+) ver (?<minor>[0-9]+) Commented Dec 7, 2016 at 10:37
  • Exactly how do I use this major and minor grouping in C# Commented Dec 7, 2016 at 10:50

2 Answers 2

1

You may use a regex with named capturing groups to capture the information you need. See the following code:

var s = "993-756-V01 ver 02a";
var result = Regex.Match(s, @"(?<major>[0-9]+)\s+ver\s+(?<minor>[0-9]+)");
if (result.Success)
{
    Console.WriteLine("Major: {0}\nMinor: {1}", 
        result.Groups["major"].Value, result.Groups["minor"].Value);
}

See the C# demo

Pattern details:

  • (?<major>[0-9]+) - Group "major" capturing 1+ digits
  • \s+ - 1+ whitespaces
  • ver\s+ - ver substring and then 1+ whitespaces
  • (?<minor>[0-9]+) - Group "minor" capturing 1+ digits
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for simplifying this for me. I had over complicated the groups using Linq this way <code>foreach (Match match in matchCollection) { List<Group> groupList = new List<Group>(match.Groups.Cast<Group>()); Group[] groupResult = groupList.Where((n) => n.Length == 2).ToArray<Group>(); if (groupResult.Length > 1) { majorVersion = groupResult[0].Value; minorVersion = groupResult[1].Value; } }</code>
Yes, that is a lot of redundant code. If my answer proved helpful, please also consider upvoting the answer.
1

Another short possibilility i see is to use the below pattern:

V(\d+)\D+(\d+)

Here:

V     = Literal `V` capital alphabet.
(\d+) = Captures any digit from 0-9 following `V` character. 
\D+   = Anything except digit next to digits. (A way to find the next numeric part of your version number)
(\d+) = Captures any digit from 0-9 following non-digit characters.

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.