Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# regular expressions. Get nth occurrence

Tags:

c#

regex

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");
like image 662
dek Avatar asked Dec 05 '22 09:12

dek


2 Answers

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];
//...
like image 190
Servy Avatar answered Dec 21 '22 06:12

Servy


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
like image 31
Soner Gönül Avatar answered Dec 21 '22 06:12

Soner Gönül