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', 'abcKKK'];
// your regular expression goes here, between the '/' characters.
var regex = /(^[A-Za-z]{3})$\d/;
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>";
}