Regex get nth value separated with slash

Viewed 113

I have a universal regex code where it uses Groups[1] value to extract the result. It's easy to extract SN and Ref by just giving a sn=(.*?)\. pattern. But it's so difficult to get for example, PKSC and V928. I have to use Groups[1] because users who use this application can choose their own value to display. It can be NC339 or PKXC.

//var source = "SN=1395939213.#variable/OGT84/PKXC/Undetermined.Thank You@{customer}"
//sometimes like this
var source = "SN=8029758034.Ref=BFO7Y95B3KN5#resolved/NC339/V928/ClearenceBBF.Brief@{supervisor}/verified"

var value = Regex.Match(source, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value
2 Answers

You can use

^(?:[^/]*/){2}([^/]+)

See the regex demo.

Details

  • ^ - start of a string
  • (?:[^/]*/){2} - two occurrences of any chars other than / and then a /
  • ([^/]+) - Group 1: one or more chars other than /.

Try following :

           string pattern = @"SN=(?'sn'\d+).*\{(?'supervisor'[^}]+)";
            string input = "SN=1395939213.#variable/OGT84/PKXC/Undetermined.Thank You@{customer}";
            Match match = Regex.Match(input, pattern);
            string sn = match.Groups["sn"].Value;
            string supervisor = match.Groups["supervisor"].Value;
Related