Regular Expression to find a string included between two characters while EXCLUDING the delimiters

前端 未结 12 2511
旧时难觅i
旧时难觅i 2020-11-21 23:49

I need to extract from a string a set of characters which are included between two delimiters, without returning the delimiters themselves.

A simple example should b

12条回答
  •  我寻月下人不归
    2020-11-22 00:15

    Most updated solution

    If you are using Javascript, the best solution that I came up with is using match instead of exec method. Then, iterate matches and remove the delimiters with the result of the first group using $1

    const text = "This is a test string [more or less], [more] and [less]";
    const regex = /\[(.*?)\]/gi;
    const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
    const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
    console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]
    

    As you can see, this is useful for multiple delimiters in the text as well

提交回复
热议问题