I have strings, and i want to find in them 2 words: 'start' and 'end'.
'start' and 'end' always come together (maybe i will have another characters between them, but if i have 'start', i will have 'end' too).
I try to do with regEx source that find the first 'start' and than his own 'end', and it will return the correct substring.
examples of strings: [i wrote in this examples index for every couple of 'start' and 'end' just for clarity (in the real strings i will not have this indexes)- the answer always between index (1)]
- something start something_needed end something
// print 'something_needed'
- start(1) something start(2) something end(2) something end(1) start something end
// print 'something start(2) something end(2) something'
- start(1) something start(2) start(3) something end(3) something start(4) end(4) something end(2) something end(1) something start(5) something end(5)
// print 'something start**(2) start(3) something end(3) something start(4) end(4) something end(2) something'
This is my solution in Javascript, but i prefer the answer in regEx only.
i find all the start, and after that all the end, and than- for every start: count++, for every end: count--. when count == 0, it the position of the correct end.
function getStartEnd(str) {
str = " "+str+" ";
var start = matchPosArr(str, /[ds
,()[]{}]+START+(?=[ds
,()[]{}])/gi);
var end = matchPosArr(str, /[ds
,()[]{}]+END+(?=[ds
,()[]{}])/gi);
var count = 0; // counter
var si = 0; // index of start array
var ei = 0; // index of end array
var isStart = false;
while (true) {
if (ei >= end.length) {
alert('error');
break;
}
else if (si >= start.length) {
ei++;
count--;
if (count == 0) {
ei--;
}
}
else if (start[si] > end[ei]) {
ei++;
count--;
}
else if (start[si] < end[ei]) {
si++;
count++;
}
if (count == 0 && isStart==true) {
break;
}
isStart = true;
}
return str.substring(start[0]+("start ".length),end[ei]);
}
function matchPosArr(str, regEx) {
var pos = [];
while ((match = regEx.exec(str)) != null) {
pos.push(match.index);
}
return pos;
}
alert( getSelectFrom(str) );
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…