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");
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];
//...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With