Regular Expressions In Javascript cosc 2328
What Do They Do? Does pattern matching on text We use the term “string” to indicate the text that the regular expression is applied to The most basic regular expression is a character, such as a If you character string is Jack is a boy it matches on the a
Special Characters Twelve characters have special meanings in regular expressions \^$.|?*+()[{ Sometimes you need to match on one of the special characters Escape the character with a backslash So, if you want to match 1+1=2 the correct regex is 1\+1=2
More on special characters Because we want to do more than simply search for literal pieces of text we need special characters The brace { is treated as a literal character, unless it is part of a repetition operator like a{,}, so you don’t need to escape it with a backslash Two special characters you may want to use for assignment 5 are the ^ (matches at the beginning of the line), and $ (matches at the end of the line)
Character Classes or Character Sets A character class matches only one out of several characters To match an a or an e, use [ae] You could use this in g[ae]y to match either gray or grey
Regular Expressions in Javascript In Javascript a regular expression is an object that describes a pattern of characters Used to perform pattern matching and “search-and-replace” functions on text See here:
Javascript RegExp Object Methods exec() – Tests for a match in a string; returns the first match test() – Tests for a match in a string; returns true or false The example code for assignment #5 uses test()
Much More There are entire books written on regular expressions Support for regular expressions are implemented in many programming languages
Help Javascript regex tutorial Really good regex reference Special characters reference _Special_characters.html _Special_characters.html Regex Tester