Practice Set, Week 10, Simple Regex Patterns
by subsari
HTML
<h3>Practice Set, Week 10, Simple RegEx Patterns</h3>
<p>Your task is to write the regular expression (on line 4) that will test for the existence of a sequence of three letters followed by three numbers, such as 'abc123'. (Note that 'zabc1234' also passes, since it contains a match.)</p>
<p>There are several ways to solve this - any of them that pass the test cases will do. Use the reference (and a RegEx tool such as Debuggex if that helps).</p>
<p>Remember that a regular expression starts and ends with a slash, and your expression goes in between, so you'll put your expression between the slashes provided. No quotes are necessary unless they are part of your expression.</p>
<p>For example, <code>/cscie\d/</code> will match the string "cscie" followed by any digit (although, subjectively, we prefer a 3 :-) ).</p>
<p>Test cases are provided. If your regular expression is correct, when you click "Run" the output will be <i>false, false, false, true, true, true</i>.</p>
<p>Output will appear below:</p>
<div id="output"></div>
CSS
#output {
width:80%;
border: 1px solid black;
padding: 1em;
}
JavaScript
var testStrings = ['a1', 'ab12', 'abcdef', 'abc1234', 'abc123', 'def456'];
// your regular expression goes here, between the '/' characters.
var regex = /(^[a-zA-Z]{3})(\d\d\d+)/;
// regex explanation
// the use of "(" and ")" are to separate logical tests (ie. separate)
// the use of "^" indicates that the string must start with
// the use of "[a-zA-Z]" indicates character classes to test for alphabet
// the use of "{3}" indicates quantifier to limit to 3 characters
// the use of "\d" indicates a digit
// the use of "+" indicates another occurrence
for (var i = 0; i < testStrings.length; i++) {
logMessage(regex.test(testStrings[i]));
}
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
if (!id) {
id = "output";
}
document.getElementById(id).innerHTML += msg + "<br>";
}