Javascript 尖括号(< 或 >)在正则表达式中是否特殊?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10095039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:50:04  来源:igfitidea点击:

Are the angle brackets (< or >) special in a regular expression?

javascriptregex

提问by Mike Depies

I am trying to get a regex expression to accept < and > as my outside delimiters to grab all the content in between them.

我试图让正则表达式接受 < 和 > 作为我的外部分隔符来获取它们之间的所有内容。

so content like such

如此内容

< tfdsfa  >

should be grabbed.

应该被抓住。

Do I have to escape the < and > characters or something?

我是否必须转义 < 和 > 字符或其他什么?

Regex generated by my script:

我的脚本生成的正则表达式:

/<[^(>)]*>/g

Code from file:

来自文件的代码:

data.method.highlight = function() {
    var x = data.syntax,
        text = data.$.span.html();
    for (var i=0, len = x.length; i < len; i++) {
        var rx;
        if (x[i].range) {
            rx = new RegExp(x[i].tag[0] + "[^(" + x[i].tag[1] + ")]*" + x[i].tag[1], "g");
            console.log(rx);
        }
        else {
            var temprx = x[i].tag[0];
            for (var z = 1; z < x[i].tag.length; z++) {
                temprx += "|" + x[i].tag[z];
            }
            rx = new RegExp(temprx, "g");
        }
        text = text.replace(rx,function (match) {
            console.log("looping - range");
            return '<span class="' + x[i].class.default + '">' + match + '</span>';
        });
        data.$.span.html(text);
    }
};

回答by davin

Neither <nor >are metacharacters inside a regular expression.

正则表达式中既不是元字符,<也不>是元字符。

This works for me:

这对我有用:

'<foo> and <bar>'.match(/<[^>]*>/g); // ["<foo>", "<bar>"]

回答by KEH9

May be you have problem because you trying to insert result into HTML and browser 'thinks' that it is a not valid HTML tag, like <blablabla>.

可能是因为您尝试将结果插入 HTML 而浏览器“认为”它是无效的 HTML 标记,例如<blablabla>.