This gist is an educational reference for understanding regular expressions. While using JavaScript, there have been a number of times when retrieval of a value from a string was needed. This may be a case where a regular expression could beused to search for patterns in the given string and return the desired value.
- Introduction
- Character Class
- Bracket Expressions
- Kleene Operators
- Grouping Constructs
- External Resources
In this example, the typing speed is calculated as a CPM value and the result is then added on the screen by using textContent() on an element with an id of #score. Additional metrics like the total correct characters and total incorrect characters are also shown on the screen. After the CPM is shown (and retrieved as a string) a regular expression searches for the CPM value with the following code:
const cpmString: string = 'CPM 450 | Correct 45 | Incorrect 23';
/* this is the regular expression to search for the cpm */
const regularExpression: RegExp = new RegExp('[^0-9]*([0-9]+)', '');
/* finds a match in the cpm string */
const cpmMatch: string | number = cpmString.match(regularExpression)
? cpmString.match(regularExpression)![1]
: 0;
console.log(cpmMatch);This code demonstrates how to use a regular expression to retrieve the CPM value generated on the trainer.html page for use in a hypothetical high-score table on the index.html page.
First, the value sought after is numerical so the match() method should recognize numerical characters. Searching for a specific class (or type) of character is possible with a Character Class. This is achieved with 0-9.
Second, the value sought after is numerical, but backtracking should be avoided, so the match() method should acknowledge both non-numerical and numerical characters. Searching for characters that are not a numerical number is possible with a Bracket Expression. This is achieved with [^0-9]. Then, using the same technique it is possible to search for characters that are exclusively numerical. This is achieved with [0-9].
Third, the value sought after is preceded by an arbitrary length of non-numerical characters so the match() method should retrieve all preceding non-numerical characters. Searching for zero or more preceding non-numerical characters is possible with a Kleene Star. This is achieved with [^0-9]*.
Fifth, the value sought after needs to be distinguished apart from every acknowledged character, so the match() method should create a group for the sought after value. Organizing the value into a group of characters is possible with a Grouping Construct. This is achieved with ([0-9]+).
A great resource to use when developing regular expressions is @regex101. When using this tool be sure to select ECMAScript as the language before embarking on development of your regular expression.
This gist is also available in a public respository created by the author ktortolini. Please, feel free to contact the author via email β ktortolini@smu.edu.