mouzfun
mouzfun

Reputation: 1

Matching second occurrence in javascript regexp

I'm completely new to regexps and syntax melts my brain, so basically i have a string which looks like this

randomtext WORD randomtext WORD neededtext BORDERWORD randomtext

Where word and borderword are different from each other, other stuff is self explanatory.

I've got as far as /(.?(WORD)){2}((.|\n)*)BORDERWORD/ but it doesn't work.

Another problem is that both randomtext and neededtext contain newline characters, which i think i solved in the matching group that tries to match neededtext ((.|\n)*) but have no idea how to make it work in the first one.

Any help will be greatly appreciated.

Edit: figured out a workaround, first match word((.|\n)*)borderword and then match the result with word((.|\n)*) Done. Doesn't seem right but it works for my purposes.

Upvotes: 0

Views: 1208

Answers (2)

James Buck
James Buck

Reputation: 1640

This should work:

\bWORD\s*((?:(?!WORD)(?:.|\n))*?)\s*BORDERWORD\b

It makes sure that you want to extract text between WORD and BORDERWORD, and that text does not contain another WORD sequence.

Capturing group 1 will contain the needed text

Regex demo

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58619

var str = "randomtext WORD randomtext WORD neededtext BORDERWORD randomtext";
var matches = str.match(/^.+? WORD .+? WORD (.+?) BORDERWORD/);
console.log(matches[1]); // neededtext

Upvotes: 0

Related Questions