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

前端 未结 12 2509
旧时难觅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:12

    If you are using JavaScript, the solution provided by cletus, (?<=\[)(.*?)(?=\]) won't work because JavaScript doesn't support the lookbehind operator.

    Edit: actually, now (ES2018) it's possible to use the lookbehind operator. Just add / to define the regex string, like this:

    var regex = /(?<=\[)(.*?)(?=\])/;
    

    Old answer:

    Solution:

    var regex = /\[(.*?)\]/;
    var strToMatch = "This is a test string [more or less]";
    var matched = regex.exec(strToMatch);
    

    It will return:

    ["[more or less]", "more or less"]
    

    So, what you need is the second value. Use:

    var matched = regex.exec(strToMatch)[1];
    

    To return:

    "more or less"
    

提交回复
热议问题