runsun pan wrote:
I am wondering why I couldn't get what I want in the following 3
cases of re:
You're expecting things to work in ways that shouldn't happen.
var p=/([a-zA-Z]+-?[a-zA-Z]+):([a-zA-Z0-9]+)/g
p.exec("style=' font-size:12'")
--[font-size:12,font-size,12] // expected
The RegExp.prototyp e.exec method attempts to find the first pattern
match in its argument. Here, it discovers "font-size:12", so the method
stops and returns an array containing details of the match. As the
global flag is set for the regular expression object, the lastIndex
property of the regular expression is modified to point just beyond the
end of the match: to the last apostrophe, in this case.
(B)
p.exec("style=' font-size:12;border-color:red'")
--[border-color:red,borde r-color,red]
That isn't actually what you receive. You've executed this straight
after the previous test, therefore the change in the lastIndex property
described above is significant. If this call was made separately, the
same result as above would be returned. That is, information about the
font-size declaration.
// expected: [font-size:12,font-size,12,
border-color:red,borde r-color,red]
That will never happen. The exec method only cares about the first (or
more generally, the next) match. Once it finds it (or the string has
been exhaustively searched with no match) the method will return.
As in a recent thread, "regexp test function behavior"[1], you too have
misunderstood how both the global flag and the exec method works. The
point of the former is, as I wrote in that thread, to allow repeated
processing by tracking where the last match ended. A follow-up call can
then resume from that point.
Some regular expression-related methods, most notably the
String.prototyp e.match and replace methods use the global flag to infer
that this repetitive process should be performed by the method itself,
using the behaviour of the RegExp.prototyp e.exec method to accomplish
that goal. If you want that same behaviour, you have to implement it
yourself:
String.prototyp e.detailedMatch = function(regExp ) {
var lastMatch = regExp.lastInde x = 0,
result = [],
match;
while ((match = regExp.exec(thi s))) {
result[result.length] = match;
if (regExp.lastInd ex == lastMatch) ++regExp.lastIn dex;
lastMatch = regExp.lastInde x;
}
return result;
};
Calling that:
'style="font-size:12;border-color:red"'.det ailedMatch(
/([a-zA-Z]+-?[a-zA-Z]+):([a-zA-Z0-9]+)/g);
would result in:
[[font-size:12,font-size,12],
[border-color:red,borde r-color,red]]
which is easy to observe with:
Array.prototype .toString = function() {
return '[' + this.join() + ']';
};
Compare that result with just the String.prototyp e.match method:
[font-size:12,border-color:red]
Mike
[1] regexp test function behavior
"HopfZ" <ho******@gmail .com>
Sun, 29 Oct 2006 12:02:42 (UTC)
<11************ **********@h48g 2000cwc.googleg roups.com>
<http://groups.google.c o.uk/group/comp.lang.javas cript/msg/87d9d504bf05393 d>