regular expressions and multiple match

A

ast

hi,

let us search a.+b in string abcabcabc

var reg = /a.+b/g;
var tab = reg.exec("abcabcabc");

document.write(tab[0]);

there are 2 possible matchs:

abcab
abcabcab

javascript choose the second one. Why not. But what is the rule ?
Does javascript always provide the longest possible match ?

If i want abcab, is there something to do ?
 
T

Thomas 'PointedEars' Lahn

ast said:
let us search a.+b in string abcabcabc

var reg = /a.+b/g;
var tab = reg.exec("abcabcabc");

document.write(tab[0]);

there are 2 possible matchs:

abcab
abcabcab

javascript choose the second one. Why not. But what is the rule ?
Does javascript always provide the longest possible match ?

(There is no "javascript".)

Yes, RTFM. Regular expressions are "greedy" by default.
If i want abcab, is there something to do ?

RTFM.


PointedEars
 
B

Bart Van der Donck

ast said:
let us search a.+b in string abcabcabc
var reg = /a.+b/g;
var tab = reg.exec("abcabcabc");
document.write(tab[0]);

there are 2 possible matchs:
abcab
abcabcab
javascript choose the second one. Why not. But what is the rule ?
Does javascript always provide the longest possible match ?

The rule is to return the (chronologically) last found match.
If i want abcab, is there something to do ?

'+' = repeat 1 or more times
'+?' = repeat 1 or more times, as few as possible

So:

var reg = /a.+?b/g;

Hope this helps,
 
L

Lasse Reichstein Nielsen

ast said:
hi,

let us search a.+b in string abcabcabc

var reg = /a.+b/g;
var tab = reg.exec("abcabcabc");
document.write(tab[0]);

there are 2 possible matchs:

abcab
abcabcab

javascript choose the second one. Why not. But what is the rule ?

The rule is that the "+" quantifier means: Match as many as possible
of the regexp it's quantifying (in this case '.').

The "as many as possible" doesn't always mean "as long as possible",
e.g.,
/(?:..|...)+/.exec("123456789")
matches only "12345678", not all nine characters.
Does javascript always provide the longest possible match ?

For the "+" quantifier, yes.
If i want abcab, is there something to do ?

Use the "+?" (non-greedy) quantifier:
/a.+?b/

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top