Expressions

by Tim Morgan

JavaScript

/foo/; // Simplest form of a regexp 
"Test".search(/e/); // returns '1' -- the position of the letter 'e'

var numpies = ("I have 6 pies".match(/\d/))[0]; // numpies is 6

/*
/cat/.test("concatenate")
true
/cat/.test("condogenate")
false
*/

/*
var notABC = /[^ABC]/;
undefined
"ABCBACCBBADABC".search(notABC)
10
"ABCBACCBBADABC".match(notABC)
["D"]
*/

"My phone number 416.444.4734, it is".match(/(\d{3}[\s\.-]\d{3}[\s.-]\d{4}|\d{10})/); // {3} means 'match exactly 3 digits'. [\s\.-] means 'match either a space, a dot, or a hyphen'

/* Check if something is an email address */
/\w@\w\.\w/; // Laziest possible solution, but pretty correct-ish
"[email protected]".match(/[A-Z\d]+\@[A-Z0-9\.]+\.[A-Z0-9]+/i) // Check with a case-insensitive match for one or more characters or digits, followed by an @, followed by one or more characters or digits, followed by a dot, followed by one or more characters or digits
/[0-9A-PR-Y]/;