Jordan Schnur
Jordan Schnur

Reputation: 1353

Javascript Regular Expressions Capture

I need to capture this: <!.This is a string.!>
It can contain anything within the <!. .!>

So I tried this: <\!\..+\.\!>/g

Which didn't work. I've been trying to fix this for days now with no success. I want to capture the whole string including the <!. .!>

Thanks for the help!

Upvotes: 0

Views: 68

Answers (2)

zx81
zx81

Reputation: 41838

EDIT Since the OP edited his post to specify that he doesn't just want to capture the string but also the delimiters, I have moved out the capturing parentheses from <!\.(.*?)\.!> to (<!\..*?\.!>)

This should do it:

var myregexp = /(<!\..*?\.!>)/m;
var match = myregexp.exec(subject);
if (match != null) {
    result = match[1];
} else {
    result = "";
}

Since JS does not support lookbehinds, the idea is to match the whole string, including the delimiters, but to only capture "My String" into Group 1. Then we inspect Group 1.

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98921

For someone that's "pretty good at Regex", this one is a no brainier.

var subject = "<!.This is a string.!>";
subject = subject.match(/<!\.(.*?)\.!>/);
console.log(subject[1]);

http://jsfiddle.net/tuga/YzLnN/1/

Upvotes: -1

Related Questions