user1207960
user1207960

Reputation:

RegEx matches two results single line as one

I have JavaScript a code

var docBodyText = document.body.innerHTML;
var patt =/<!--:.+:-->/g;
patt.compile(patt);
var matchesB=docBodyText.match(patt)

and a HTML page

<body>
<span><b><!--:?time:--> <!--:?date:--></b></span>
<br />
<!--:?url:-->
</body>

When I execute the script it returns
["<!--:?time:--><!--:?date:-->","<!--:?url:-->"]

but I want
<!--:?time:--> and <!--:?date:--> to be returned separately.

Upvotes: 0

Views: 119

Answers (3)

Stelian Matei
Stelian Matei

Reputation: 11623

Try to change the pattern to exclude other > tags:

var patt =/<!--:[^>]+:-->/g;

Upvotes: 0

Corubba
Corubba

Reputation: 2243

Javascript regex are greedy by default. You need to use the non-greedy qualifier for this to get the shortes matching string.

var patt =/<!--:.+?:-->/g;

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839074

You are matching greedily. The + by default means "1 or more times, but prefer as many as possible". Add a ? modifier after the + to make it match lazily:

var patt =/<!--:.+?:-->/g;

Upvotes: 1

Related Questions