<html><body><script>
var matches = /(\w+)(\s*(\w+))?/.exec("aaa");
alert(matches.length);
alert(typeof(matches[3]));
</script></body><html>
I'm really new to regular expressions, so this may be a very easy question.
The regular expression above /(\w+)(\s*(\w+))?/ matches patterns like "aaa", "123", "my_var" or "aaa bbb", "123 456", "my_var my_value".
For an expression like "aaa bbb", matches = ["aaa bbb", "aaa", " bbb", "bbb"], but for an expression like "aaa", matches = ["aaa", "aaa", ???, ???]
The first thing that surprised me is that matches.length = 4. I was expecting it to be 2, but I don't see any document explaining what it should be. How does it work?
And the second thing that surprised me is that the 2 "extra" matches that I got are working different in the 2 browsers I've tested this into:
In Firefox 3.6.3, matches[2] and matches[3] are undefined.
In Internet Explorer 6, matches[2] and matches[3] are an empty string.
Basically, how should I check if I've got a "short" (like "aaa") or a "long" (like "aaa bbb") expression?