匹配上的替换字符串条件

时间:2015-04-16 08:33:19

标签: javascript regex replace sublimetext2 sublimetext3

我想知道在大多数正则表达式搜索和替换机制中是否可以根据是否发生某个匹配来有条件地替换文字字符串。我的工作示例是正则表达式替换的

^(\s*([\S]*):.*function.*\((.+)\).*\{.*)$ - > \1 console.info('\2 ::: \3:', \3); ^(\s*([\S]*):.*function.*\(\).*\{.*)$ - > \1 console.info('\2');

第一个替换以下行:

test: function (arg1, arg2) {
    //pass
}

使用:

test: function (arg1, arg2) { console.info('test2 ::: arg1, arg2:', arg1, arg2);
    //pass
}

,第二个对没有参数的函数也是如此:

test2: function () {
    //pass
}

我正在寻找一种方法,只应用一次搜索和替换来执行这两项这些任务。一种方法,如果这是可能的话,基本上是说"如果我有\3,则替换::: \3:', \3,否则不要。这可能吗?还有另一种方式吗?

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

var code = document.getElementById("code");
code.value = code.value.replace(/\b(function\s*(?:[\w.]+)?)\s+\((.*?)\)\s*{/g,function(match,p1,p2) {
    if (p2.length) {
        return match + "console.info('test2 ::: arg1, arg2:', p1, p2);"
    } else {
        return match + "console.info('other contents');"
    }
})

如果您的参数是简单值*,您可以执行类似这样的操作

var code = document.getElementById("code");
code.value = code.value.replace(/\b(function\s*(?:[\w.]+)?)\s+\((.*?)\)\s*{/g,function(match,p1,p2) {
    if (p2.length) {
        var ParamsCount = p2.split(",").length;
        var ParamString = []
        for (p=0;p<ParamsCount;p++) {
            ParamString[p] = "'Arg" + p + ": ' + " + "arguments[" + p +"]"
        }
        return match + "console.log(" + ParamString.join(", ") + ")"
    } else {
        return match + "console.info('other contents');"
    }
})
  • 因为它基于逗号进行了基本的分割,所以带有嵌套逗号的参数会导致问题..例如function foo(bar(1,2),"sample") {function foo("hey, that's cool")会搞砸参数。

正则表达式解释

`\b`                    # Token: \b (word boundary)
`(`                     # Opens CG1
    `function`          # Literal function
    `\s*`               # Token: \s (white space)
                          # * repeats zero or more times
    `(?:`               # Opens NCG
        `[\w.]+`        # Character class (any of the characters within)
                          # Token: \w (any alpha or numeric character)
                          # Any of: .
                          # + repeats one or more times
    `)?`                # Closes NCG
                          # ? repeats zero or one times
`)`                     # Closes CG1
`\s+`                   # Token: \s (white space)
                          # + repeats one or more times
`\(`                    # Literal (
`(`                     # Opens CG2
    `.*?`               # . denotes any single character, except for newline
                          # * repeats zero or more times
                          # ? as few times as possible
`)`                     # Closes CG2
`\)`                    # Literal )
`\s*`                   # Token: \s (white space)
                          # * repeats zero or more times
`{`                     # Literal {

JSFiddle(两者的演示,只是取消注释单个评论的返回):http://jsfiddle.net/rg23LL0p/