I have a text extracted from a large PDF file. I am only interested in one part of this text. I only need the part which is present between 2 test substrings AND which has 1 or more occurrences of a specific word XX12QW. Out of those 2 test substrings/words, the first one can be included in the match as shown in the desired output below
Input String:
test
abc def
test 123
test pqr
XX12QW
jkl XX12QW hjas
12asd23 test bxs
Desired Output:
test pqr
XX12QW
jkl XX12QW hjas
12asd23
Things to be noted:
test.test which contain 1 or more occurrences of the word XX12QW. This word XX12QW will not be present at all between any other pairs of the word - test. That is, there will never be a case like this: test abc XX12QW test isadkj XX12QW test an testXX12QW is present between test and $(End of string/file):
test absjh123 sjnc test jhsd32 test aabb XX12QW asdj XX12QW sdfktest aabb XX12QW asdj XX12QW sdfkI am stuck on this for a long time now and really need someone else to look at it.
Regex: test[\s\S]*?XX12QW[\s\S]*?(?=test)
Would really appreciate any help.
A pure regex solution is possible, but it would be best to split with test and grab the item that contains XX12QW from the array and appen the test at the start:
var s = "test \nabc def \ntest 123 \ntest pqr \nXX12QW\njkl XX12QW hjas \n12asd23 test bxs";
var res = s.split('test').slice(1) // Split with 'test' and remove 1st item
.filter(function(x) {return ~x.indexOf("XX12QW");}) // Keep those with XX12QW
.map(function(y) {return ("test"+y).trim();}); // Append test back and trim
console.log(res);
A single regex solution can look like
/test(?:(?!test)[^])*?XX12QW[^]*?(?=\s*test)/
See the regex demo
Details
test - a literal test substring(?:(?!test)[^])*? - a tempered greedy token matching any char, 0+ chars, as few as possible, other than those starting a test char sequenceXX12QW - a literal XX12QW substring[^]*? - any 0+ chars, as few as possible, up to (and excluding...)(?=\s*test) - 0+ whitespaces followed with the test substring.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With