dek
dek

Reputation: 85

C# regular expressions. Get nth occurrence

hi i am trying to split a string using regx. How do i get the nth occurrence of a pattern so i could assign it to a string?

var myString = "1.2.300.4";
var pattern = new Regex(@"([0-9]+)");

var major = pattern.Occurrence(1); //first occurrence
var minor = pattern.Occurrence(2) //second occurrence
var build = pattern.Occurrence(3) //third occurrence
var revision = pattern.Occurrence(4) // forth occurrence

something to that effect but in regex.

is there a way to choose the occurrence in the regex pattern itself? eg;

var major = new Regex(@"([0-9]+)$1");
var minor = new Regex(@"([0-9]+)$2");
var build = new Regex(@"([0-9]+)$3");
var revision = new Regex(@"([0-9]+)$4");

Upvotes: 4

Views: 6734

Answers (5)

dek
dek

Reputation: 85

Resolved...

This is as close as i can get to the idea i have in my head using Regex. And it works for a string of any known length.

var myString = "1.2.300.4.50.6000.70";
var pattern = new Regex(@"([0-9]+)");
var match = pattern.Matches(myString);

var secondOccurrence = match[1]; // 2
var fifthOccurrence = match[5];  // 6000

Thanks everyone for your help.

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98740

You can use String.Split method like;

var myString = "1.2.300.4";
var array = myString.Split(new char[] {'.'}, StringSplitOptions.RemoveEmptyEntries);
foreach (var element in array)
{
    Console.WriteLine (element);
}

Outputw will be;

1
2
300
4

Here a DEMO.

As an alternative, using System.Version could be better option for some cases. Like;

Version v = new Version("1.2.300.4");
Console.WriteLine (v.Major);
Console.WriteLine (v.Minor);
Console.WriteLine (v.Build);
Console.WriteLine (v.Revision);

Output will be;

1
2
300
4

Upvotes: 5

EZI
EZI

Reputation: 15354

var version = Version.Parse("1.2.300.4");

var major = version.Major;
var minor = version.Minor;
var build = version.Build;
var revision = version.Revision;

Upvotes: 1

Vulcronos
Vulcronos

Reputation: 3456

Use string.Split('.').

The result will be an array.

var myString = "1.2.300.4";
var myResults = myString.Split('.');

var major = myResults[0]; //first occurrence
var minor = myResults[1]; //second occurrence
var build = myResults[2]; //third occurrence
var revision = myResults[3]; // forth occurrence

Upvotes: 1

Servy
Servy

Reputation: 203814

You can use Match to find the first, and then NextMatch on each match to get the next.

var major = pattern.Match(myString);
var minor = major.NextMatch();
var build = minor.NextMatch();
var revision = build.NextMatch();

If you don't want to lazily iterate the matches you can use Matches to parse the whole string and then get the matches (if you want) by index):

var allmatches = pattern.Matches(myString);
var major = allmatches[0];
//...

Upvotes: 9

Related Questions