JRS: In article <bf**********@sparta.btinternet.com>, seen in
news:comp.lang.javascript, Adam David Moss
<ad****@nospamglobalnet.co.uk> posted at Sun, 20 Jul 2003 16:35:38 :-
Hello,
I have a requirement whereby I must validate that a string matches one of
several patterns:
1. An ISO standard 2 character country code (eg GB, NL) followed by five
digits.
2. An ISO standard 2 character country code (eg GB, NL) followed by an X
followed by five digits.
3. 3 characters in the range a-z followed by 3 digits followed by 2
characters in a specific set (eg MT, AT, DA).
4. 4 characters followed by a hash (#) followed by 3 characters followed by
3 digits followed by a hash followed by 3 characters.
5. 4 characters followed by a hash (#) followed by 3 characters followed by
3 digits followed by a hash followed by 4 characters.
I have been told that a better way to achieve this than using .charAt is by
using something called a regular expression,
Agreed.
but I don't really understand
them. Can anyone please advise on the above
Some may construct a single vast RegExp to do it. I would merge 12 & 45
only. Ignoring that some 2-letter patterns are not at present
countries, to get started,
function TryIt(S) {
if (/^([A-Z]{2})X?\d{5}$/.test(S)) return 12
if (/^([a-z]{3})\d{3}([A-Z]{2})$/.test(S)) return 3
if (/^....#...\d{3}#....?$/.test(S)) return 45
return 0 } // lightly tested
The result may be used as, or cast to, a boolean; or used to show which
rule fired.
In the first two cases, RegExp.$1 (& RegExp.$2) contained matched
fields, which can be tested against a list of valid ones :
OK = "UK NL RU MX ...".indexOf(RegExp.$1+" ") != -1 // lightly tested
or alternatively point me in
the direction of a suitable resource on these regular expression things?
Dillons, Waterstones, maybe Foyles, etc.; any good Public, College, or
University Library.
Before going, read <URL:http://www.merlyn.demon.co.uk/js-other.htm#RE>,
to get a slight general idea.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.