Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
    }
};
like image 437
Mike Depies Avatar asked Apr 10 '12 19:04

Mike Depies


People also ask

What do the [] brackets mean in regular expressions?

Square brackets ( “[ ]” ): Any expression within square brackets [ ] is a character set; if any one of the characters matches the search string, the regex will pass the test return true.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Is a special character in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).


1 Answers

Neither < nor > are metacharacters inside a regular expression.

This works for me:

'<foo> and <bar>'.match(/<[^>]*>/g); // ["<foo>", "<bar>"]
like image 147
davin Avatar answered Sep 20 '22 13:09

davin