Robert Nagel
Robert Nagel

Reputation: 59

RegEx Grouping after keyword

I am stuck on a Regex problem. Sample Text

data-key=foo1,
data-key=foo2,
data-key=foo3,
BAR,
data-key=foo4,
asd
data-key=foo5,
asfda
data-key=foo6,

I now want all data-key lines after the word "BAR". Desired Result:

data-key=foo4,
data-key=foo5,
data-key=foo6,

This RegEx would give me the result I want, but I don´t want to specify how many times the data-key line occurs, as it could be any number:

(?s)BAR.*(data-key.*?,).*(data-key.*?,).*(data-key.*?,)

Any ideas?

Upvotes: 2

Views: 65

Answers (2)

bobble bubble
bobble bubble

Reputation: 18490

With any regex flavor at least supporting lookaheads to check BAR is not ahead.

(data-key[^,\n]*,).*(?![\s\S]*?\nBAR)

See this demo at regex101  (using a capturing group to extract the part until comma)


If using PCRE, there is (*SKIP)(*F) available to skip some part.

(?m)(?s:\A.*?^BAR)(*SKIP)(*F)|^data-key.*?,
  • (?m) flag for multline mode to make the caret match line start and the dollar line end
  • \A matches start of the string
  • (?s: starts a non capturing group with dotall flag to make the dot match newlines

See another demo at regex101

Upvotes: 3

Pavel Lint
Pavel Lint

Reputation: 3527

Unless you're asking this for theoretical reasons, I'd suggest just splitting your input by BAR and then executing a regexp on everything after it:

var str="data-key=foo1,\ndata-key=foo2,\ndata-key=foo3,\nBAR,\ndata-key=foo4,\nasd\ndata-key=foo5,\nasfda\ndata-key=foo6";

var regex = /(?:data-key=([^,]*))/ig;
 
var matches = Array.from(str.split("BAR,")[1].matchAll(regex));

console.log(matches);

This gives you the result you're looking for.

Upvotes: 1

Related Questions