user2188559
user2188559

Reputation: 13

find value after nth occurence of - using RegEx

This expression

[A-Z]+(?=-\d+$)

find SS and BCP from following string

ANG-B31-OPS-PMR-MACE-SS-0229

ANG-RGN-SOR-BCP-0004

What I want to do is find the value after third "-" which is PMR in first string and BCP in second string

Any help will be highly appreciated

Upvotes: 0

Views: 207

Answers (3)

VladL
VladL

Reputation: 13033

The lookbehind and lookahead will exclude the pre and post part from the match

string mus = "ANG-B31-OPS-PMR-MACE-SS-0229";

string pat = @"(?<=([^-]*-){3}).+?(?=-)";
MatchCollection mc = Regex.Matches(mus, pat, RegexOptions.Singleline);
foreach (Match m in mc)
{
    Console.WriteLine(m.Value);
}

Upvotes: 1

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

If you have the option it would be simpler to locate the third "-" and take a substring of the input. See nth-index-of.

var input = "ANG-B31-OPS-PMR-MACE-SS-0229";
input = input.Substring(input.NthIndexOf("-", 3) + 1, 3);

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

What about simple String.Split?

string input = "ANG-B31-OPS-PMR-MACE-SS-0229";
string value = input.Split('-')[3]; // PMR

Upvotes: 0

Related Questions