4

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");
4

5 回答 5

9

您可以使用Match查找第一个,然后NextMatch在每个匹配项上获取下一个。

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

如果您不想懒惰地迭代匹配项,您可以使用它Matches来解析整个字符串,然后通过索引获取匹配项(如果需要):

var allmatches = pattern.Matches(myString);
var major = allmatches[0];
//...
于 2013-10-02T19:51:23.773 回答
4

您可以使用String.Split类似的方法;

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

输出w将是;

1
2
300
4

这里一个DEMO.

作为替代方案,System.Version在某些情况下使用可能是更好的选择。喜欢;

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

输出将是;

1
2
300
4
于 2013-10-02T19:50:14.603 回答
1

利用string.Split('.').

结果将是一个数组。

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
于 2013-10-02T19:51:34.370 回答
1

解决...

这与我使用正则表达式的想法很接近。它适用于任何已知长度的字符串。

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

感谢大家的帮助。

于 2013-10-06T00:09:37.120 回答
1
var version = Version.Parse("1.2.300.4");

var major = version.Major;
var minor = version.Minor;
var build = version.Build;
var revision = version.Revision;
于 2013-10-02T19:58:18.677 回答