正则表达式匹配str中的javascript / php函数名称

时间:2014-04-20 07:04:22

标签: javascript jquery regex

我试图突出显示代码(并最终清理HTML),但我的正则表达式不仅仅匹配函数名称和参数。我不擅长正则表达式,有点让我很开心。此外,当我尝试在匹配结果上使用.replace()来清理HTML并添加<pre>括号时,它会给我错误Uncaught TypeError: undefined is not a function我猜是因为它是因为它没有返回基本字符串?

var content = $('#content'),
    html = content.html(),
    result = html.replace(/\s.*\(.*\)\s/gi, "<pre>$&</pre>");

    // When trying to add the <pre> tags in the last line of code
    // And use this to sanitize my html.match() I get a error

    // escapedRes = result.replace(/&/g, "&amp;")
    //           .replace(/</g, "&lt;")
    //           .replace(/>/g, "&gt;")
    //           .replace(/"/g, "&quot;")
    //           .replace(/'/g, "&#039;");

    // Uncaught TypeError: undefined is not a function 

content.html(result);

JSFiddle Example

破碎的消毒小提琴

var content = $('#content'),
    html = content.html(),
    result = html.match(/\w+\(.+?\)/g);
var escapedRes = result.replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
    .replace(/(/g, "&#40;")
    .replace(/)/g, "&#41;")
    .replace(/\*/g, "&#42;")
    .replace(/$/g, "&#36;");
var result = escapedRes.replace(result, '<pre>'+escapedRes+'</pre>');
content.html(result);

JSFiddle Example

1 个答案:

答案 0 :(得分:3)

使用此正则表达式:

/\w+\(.+?\)/g

DEMO

更新

在您的消毒部分,您需要

 result = html.match(/\w+\(.+?\)/g)[0];

as match()返回一个数组。

此外,您需要使用反斜杠转义()以及$,因为它们在正则表达式中具有特殊含义。