PDA

View Full Version : RegExp ques. Need better understanding of :?


x_goose_x
05-05-2003, 12:34 AM
I have a string that contains the path to an image. The images are always named like x11 (a letter, then one or two digits). I want to extract the number of the image, disregarding the starting character. At first I tried the following:


myString = img.src;
alert(/[0-9]{1,2}(?:\.gif)/.exec(myString));


Where by my understanding, searches for a single or double digit, followed by ".gif", but only returns the number. This did NOT work. After playing around a bit, I tried:


myString = img.src;
alert(/[0-9]{1,2}(?=\.gif)/.exec(myString));


which works perfectly. My question is, why didn't my original code work? Am I using the ?: incorrectly?

liorean
05-05-2003, 01:16 AM
(?:pattern) is non-capturing match - in other words a way to group several characters but not consume a backreference by storing them. It operates in it's position in the regex, exaxtly as were it a catching match. Note that the pattern is part of the match.

(?=pattern) on the other hand is a lookahead. So if the regex to that point is followed by the lookahead, it matches. In other words, the lokahead isn't part of the match. So, to give you an example:

/lio(rean)/.exex('liorean') => ['liorean', 'rean']
/lio(?:rean)/.exex('liorean') => ['liorean']
/lio(?=rean)/.exex('liorean') => ['lio']
/lio(?=rean)/.exex('lion') => null
/lio(?!rean)/.exex('liorean') => null
/lio(?!rean)/.exex('lion') => ['lio']

Read more in my article, <http://wsabstract.com/javatutors/redev.shtml>

x_goose_x
05-05-2003, 02:16 AM
On the following link:
http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/regexp.html
It said that ?: was non-capturing, and from what you said:
/lio(?:rean)/.exex('liorean') => ['liorean']
and from my own tests, it obviously is.

Algorithm
05-05-2003, 06:01 AM
x_goose_x: Non-capturing regExp clauses were introduced in JavaScript 1.5, so not all browsers support it.

liorean
05-05-2003, 06:35 AM
I believe they are ECMA262-3...