Regular expression to match single bracket pairs but not double bracket pairs

后端 未结 2 1474
盖世英雄少女心
盖世英雄少女心 2021-01-19 12:11

Is it possible to make a regular expression to match everything within single brackets but ignore double brackets, so for example in:

{foo} {bar} {{baz}}
         


        
2条回答
  •  猫巷女王i
    2021-01-19 12:47

    To only match foo and bar without the surrounding braces, you can use

    (?<=(?

    if your language supports lookbehind assertions.

    Explanation:

    (?<=      # Assert that the following can be matched before the current position
     (?

    EDIT: In JavaScript, you don't have lookbehind. In this case you need to use something like this:

    var myregexp = /(?:^|[^{])\{([^{}]*)(?=\}(?!\}))/g;
    var match = myregexp.exec(subject);
    while (match != null) {
        for (var i = 0; i < match.length; i++) {
            // matched text: match[1]
        }
        match = myregexp.exec(subject);
    }
    

提交回复
热议问题