Prithvi Uppalapati
Prithvi Uppalapati

Reputation: 800

Regex pattern match by delimiter

to get the value of gs from the below query.

(2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38')

I have tried with below pattern

(?<=gs=)(.*)([|])

But this results gs=accounting asdf* |gs=tax*|12|

Desired output should be : accounting asdf*,tax*

is that possible with change in pattern ?

Upvotes: 1

Views: 396

Answers (2)

Robb
Robb

Reputation: 3851

This regex will match as you want.

(?<=gs=)([^|)]*)

It will also handle the case where gs is the last clause without including the closing bracket in the group.

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

I suggest 2 solutions, see their online demo.

One is regex-based:

var x = "(2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38')";
var result = Regex.Matches(x, @"(?:^|\|)gs=([^|]*)")
    .Cast<Match>()
    .Select(p => p.Groups[1].Value)
    .ToList();
foreach (var s in result)
    Console.WriteLine(s);

NOTE that the (?:^|\|)gs=([^|]*) pattern will only match gs= at the string beginning or after |, and then ([^|]*) will capture zero or more chars other than | into Group 1 that you will collect later with Select. See the regex demo.

Or a non-regex based, just split with |, check if the item starts with gs=, and then split with = to get the last part:

var res2 = x.Split('|')
        .Where(p => p.StartsWith("gs="))
        .Select(n => n.Split('=').LastOrDefault())
        .ToList();
    foreach (var t in res2)
        Console.WriteLine(t);

Upvotes: 1

Related Questions