Dr John Stockton wrote:
ISTM that RegExps deserve a FAQ entry, with links to more
detailed sources.
An important question, probably not treated by many otherwise
worthwhile sources, must be on feature detection of the newer
RegExp facilities - for example, greedy/non-greedy.
The answer may be that it is not possible to do so in a safe
manner; that one can do no better than something like
document.write("Testing non-greedy :- ")
X = /<trialRegExp>/.test(string)
document.write("survived.")
That is, nevertheless, a useful answer; if it is right, it
prevents the naive seeking anything better, and if it is
wrong someone will soon say so.
Where a page requires an advanced RegExp facility, it is
best to have a controlled failure at a well-chosen point.
<snip>
A little provisional testing suggest that the regular expression
features (such as non-greedy) may not be that difficult to feature
detect. Trying some reg ex syntaxes that should be problematic on older
browsers did not result in any errors, just different results. Which
means that using String.replace (at least) on a test string it should be
reasonable to assume that the regular expression implementation supports
the required feature if the resulting string equal the expected result.
The following examples list the operation used and the resulting strings
on various browsers, including a couple of dinosaurs.
"a".replace(/a??/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
X X a Xa Xa Xa
"aaaa".replace(/(a){2,4}?/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
X X aaaa Xaa Xaa Xaa
"aaaa".replace(/(a){2,}?/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
X X aaaa Xaa Xaa Xaa
"aaaab".replace(/a(?=b)/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
aaaab aaaab aaaab aaaXb aaaXb aaaXb
"aaaab".replace(/a(?:b)/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
aaaab aaaab aaaab aaaX aaaX aaaX
"aaaab".replace(/a(?!b)/, 'X')
HotJava3 Net 4 Opera 6 Opera 7 Mozilla 1.3 IE 6
aaaab aaaab aaaab Xaaab Xaaab Xaaab
Obviously I don't know for sure that these tests will not produce errors
on any browsers. It would certainly be worth seeing what IE 4 makes of
them.
Richard.