Regular expression 101

Regular expressions allow us to describe a pattern of characters. They are used for matching and extracting values from strings. For example, if we had a string that contained digits (1,2,3) at various positions, a regular expression would allow us to easily retrieve them:

const string = 'some 1 content 2 with 3 digits';
string.match(/1|2|3/g); // => ["1", "2", "3"]

A regular expression is written as a pattern delimited by forward slashes, with optional flags following the final forward slash:

/[PATTERN]/[FLAGS]

The pattern you write can contain both literal and special characters that together inform the regular expression engine of what to look for. The regular expression we're using in our example contains literal characters (that is, 1, 2, 3) and the pipe (that is, |) special character:

/1|2|3/g

 The pipe special character tells the regular expression engine that the characters on the left or the right of the pipe may match. The g, following the final forward slash, is a global flag that directs the engine to search globally within the string and not to give up after the first match is found. For us, this means that our regular expression will match either "1", "2", or "3", wherever they appear within a subject string.

There are specific special characters we can use within regular expressions that act as shortcuts. The notation [0-9] is an example of this. It is a character class that will match all the digits from 0 to 9 so that we don't have to list all of these digits individually. There is also a shorthand character class, d, that allows us to express this even more succinctly. Thus, we can shorten our regular expression to the following:

/d/g

For a more realistic application, we may imagine a scenario in which we wish to match sequences of digits, such as phone numbers. Perhaps we wish to match only those phone numbers beginning with 0800 and containing a further 4 to 6 digits. We could do this with the following regular expression:

/0800d{4,6}/g

Here, we are using the {n, n} syntax, which allows us to express a quantity for the preceding special character, d. We can confirm that our pattern works  by passing it to a test string's match method:

`
This is a test in which exist some phone
numbers like 0800182372 and 08009991.
`.match(
/0800d{4,6}/g
);
// => ["0800182372", "08009991"]

This brief introduction only touches on the very surface of what regular expressions can do. The syntax of regular expressions allows us to express significant complexity, allowing us to validate that specific text exists within a string or to extract specific text for use within our programs. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.71.237