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

前端 未结 12 2506
旧时难觅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"
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 00:16

    If you need extract the text without the brackets, you can use bash awk

    echo " [hola mundo] " | awk -F'[][]' '{print $2}'

    result:

    hola mundo

    0 讨论(0)
  • 2020-11-22 00:18

    You just need to 'capture' the bit between the brackets.

    \[(.*?)\]
    

    To capture you put it inside parentheses. You do not say which language this is using. In Perl for example, you would access this using the $1 variable.

    my $string ='This is the match [more or less]';
    $string =~ /\[(.*?)\]/;
    print "match:$1\n";
    

    Other languages will have different mechanisms. C#, for example, uses the Match collection class, I believe.

    0 讨论(0)
  • 2020-11-22 00:20

    This one specifically works for javascript's regular expression parser /[^[\]]+(?=])/g

    just run this in the console

    var regex = /[^[\]]+(?=])/g;
    var str = "This is a test string [more or less]";
    var match = regex.exec(str);
    match;
    
    0 讨论(0)
  • 2020-11-22 00:22

    PHP:

    $string ='This is the match [more or less]';
    preg_match('#\[(.*)\]#', $string, $match);
    var_dump($match[1]);
    
    0 讨论(0)
提交回复
热议问题