Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

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

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);
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Neither < nor > are metacharacters inside a regular expression.

This works for me:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...