Get string between 2 words, that contain this words inside him too

后端 未结 3 808
遥遥无期
遥遥无期 2020-12-12 05:34

I have strings, and i want to find in them 2 words: \'start\' and \'end\'.

\'start\' and \'end\'

3条回答
  •  既然无缘
    2020-12-12 05:56

    I'm having a hard time understanding what you exactly want, but if I understand correctly: you cannot do this with pure regex in javascript because lookbehind (positive (?<=...) and negative (?) is not supported, and thus you would not be able to match the 'start(n)' before the match result.


    but instead you can use subgroups (subgroups aren't fully supported in javascript so you'll need to use replace):

    var string = "something start(1) something_needed end(1) something";
    var regex = /start\((\d+)\)(.*)end\(\1\)/;
    string.replace(regex, function($0, $1, $2) {
    
        var result = $2;
        console.log($2)
        //do stuff with $2 here
    });
    

    $0 is the original match (start\((\d+)\)(.*)end\(\1\))

    $1 and $2 are the groups that are outputted by the regex.

    $1 refers to (\d+). It's already used to 'store' the number behind start (1 in this case). But here's where the magic happens: it gets loaded again and matched against with \1 inside the regex.

    $2 is where the info you need is stored. it refers to (.*)

提交回复
热议问题