SoFunction
Updated on 2025-03-04

Introduction to JS regular expression usage

Detailed explanation of regular expression usage

Introduction

Simply put, regular expressions are a powerful tool that can be used for pattern matching and replacement. Its functions are as follows:
Tests a pattern of a string. For example, you can test an input string to see if there is a phone number pattern or a credit card number pattern in the string. This is called data validation.
Replace text. You can use a regular expression in a document to identify a specific text, and then you can delete it all, or replace it with another text.
Extract a substring from the string according to pattern matching. Can be used to find specific text in text or input fields.

Basic syntax

After gaining a preliminary understanding of the functions and functions of regular expressions, let’s take a look at the syntax format of regular expressions in detail.

The form of regular expressions is generally as follows:

/love/The part between the "/" delimiter is the pattern to match in the target object. The user just needs to put the pattern content of the matching object in the "/" delimiter. To enable users to customize pattern content more flexibly, regular expressions provide special "metachars". The so-called metacharacter refers to those special characters with special meaning in regular expressions, which can be used to specify the appearance pattern of their leading characters (that is, characters that are before the metacharacter) in the target object.
The more commonly used metacharacters include: "+", "*", and "?".
The "+" metacharacter specifies that its leading character must appear once or more consecutively in the target object.
The "*" metacharacter specifies that its leading character must appear zero or multiple consecutive times in the target object.
The "?" metacharacter specifies that its leading object must appear zero or once in a row in the target object.

Next, let's take a look at the specific application of regular expression metacharacters.

/fo+/ Because the above regular expression contains the "+" metacharacter, it can match a string such as "fool", "fo" or "football" in the target object that appears one or more letters o in succession after the letter f.
/eg*/Because the above regular expression contains the "*" metacharacter, it means that it can match a string with zero or more letters g in the target object, such as "easy", "ego", or "egg" in the target object, which appears in succession after the letter e.
/Wil?/Because the above regular expression contains the "?" metacharacter, it means that it can match the string of zero or one letter l in the target object, etc., which appears successively after the letter i.

Sometimes I don't know how many characters to match. To be able to adapt to this uncertainty, regular expressions support the concept of qualifiers. These qualifiers can specify how many times a given component of a regular expression must appear before the match can be met.

{n} n is a non-negative integer. Match the n times that are determined. For example, 'o{2}' cannot match 'o' in "Bob", but can match two os in "food".
{n,} n is a non-negative integer. Match at least n times. For example, 'o{2,}' cannot match 'o' in "Bob" but can match all os in "fooooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m} m and n are non-negative integers, where n <= m. Match at least n times and match up to m times. For example, "o{1,3}" will match the first three os in "fooooooood". 'o{0,1}' is equivalent to 'o?'. Please note that there cannot be spaces between commas and two numbers.
In addition to metacharacters, users can also specify exactly how often the pattern appears in the matching object. For example, /jim {2,6}/ The above regular expression stipulates that the character m can appear 2-6 times in the matching object, so the above regular expression can be matched with strings such as jimmy or jimmmmy.

After gaining a preliminary understanding of how to use regular expressions, let's take a look at how to use several other important metacharacters.
\s: used to match a single space character, including tab keys and line breaks;
\S: Used to match all characters except a single space character;
\d: used to match numbers from 0 to 9;
\w: Used to match letters, numbers or underscore characters;
\W: Used to match all characters that do not match \w;
.: Used to match all characters except line breaks.

(Note: We can regard \s and \S and \w and \W as inverse operations)

Next, we will take an example to see how to use the above metacharacter in regular expressions.

/\s+/ The above regular expressions can be used to match one or more space characters in the target object.
/\d000/ If we have a complex financial statement in our hands, we can easily find all payments with a total amount of 1,000 yuan through the above regular expression.
In addition to the metacharacters we have introduced above, regular expressions also have another unique special character, namely, locators. Locators are used to specify where the matching pattern appears in the target object. More commonly used locators include: "^", "$", "\b" and "\B".
"^" locator specifies that the matching pattern must appear at the beginning of the target string
The "$" locator specifies that the matching pattern must appear at the end of the target object
"\b" locator specifies that the matching pattern must appear at one of the two boundaries at the beginning or end of the target string
The "\B" locator specifies that the matching object must be within the two boundaries of the beginning and end of the target string.
That is, the matching object cannot be used as the beginning of the target string or the end of the target string.
Similarly, we can also regard "^" and "$" and "\b" and "\B" as two sets of locators that are inverse operations. For example: /^hell/ Because the above regular expression contains the "^" locator, it can match a string starting with "hell", "hello" or "hellhound" in the target object. /ar$/ Because the above regular expression contains the "$" locator, it can be matched with a string ending in "car", "bar" or "ar" in the target object. /\bbom/ Because the above regular expression pattern starts with the "\b" locator, it can match a string starting with "bomb", or "bom" in the target object. /man\b/ Because the above regular expression pattern ends with the "\b" locator, it can be matched with a string ending with "human", "woman" or "man" in the target object.
In order to facilitate users to set matching patterns more flexibly, regular expressions allow users to specify a certain range in the matching patterns without being limited to specific characters. For example:
/[A-Z]/The above regular expression will match any capital letter in the range A to Z.
/[a-z]/The above regular expression will match any lowercase letter in the range from a to z.
/[0-9]/ The above regular expression will match any number in the range from 0 to 9.
/([a-z][A-Z][0-9])+/ The above regular expression will match any string composed of letters and numbers, such as "aB0", etc.

One thing that needs to be reminded here is that you can use "()" in regular expressions to combine strings together. The contents of the "()" symbol must appear in the target object at the same time. Therefore, the above regular expression will not be able to match a string such as "abc" and so on, because the last character in "abc" is a letter rather than a number.
If we want to implement "or" operations similar to programming logic in regular expressions and choose one of multiple different patterns to match, we can use the pipeline character "|". For example: /to|too|2/ The above regular expression will match "to", "too", or "2" in the target object.
There is also a more commonly used operator in regular expressions, namely the negative character "[^]". Unlike the locator "^" we introduced earlier, the negative character "[^]" stipulates that the string specified in the pattern cannot exist in the target object. For example: /[^A-C]/The above string will match any character in the target object except A, B, and C. Generally speaking, when "^" appears in "[]", it is regarded as a negative operator; when "^" is outside "[]", or there is no "[]", it should be regarded as a locator.
Finally, when the user needs to add metacharacters to the pattern of the regular expression and find their matching object, the escape character "\" can be used. For example: /Th\*/ The above regular expression will match "Th*" instead of "The" in the target object.

After constructing a regular expression, you can evaluate the value like a mathematical expression, that is, you can evaluate it from left to right and in a priority order. The priority is as follows:

1.\ escape character
2.(), (?:), (?=), [] brackets and square brackets
3.*, +, ?, {n}, {n,}, {n,m} qualifiers
4.^, $, \anymetacharacter Position and Order
5.|"OR" operation

Examples of usage

There is a powerful RegExp() object in JavaScript 1.2 that can be used to match regular expressions. The test() method can check whether the target object contains a matching pattern and return true or false accordingly.
We can use JavaScript to write the following script to verify the validity of the email address entered by the user.
Regular expression object
This object contains regular expression patterns and flags indicating how the patterns are applied.
Syntax 1 re = /pattern/[flags]
Syntax 2 re = new RegExp("pattern",["flags"])
parameter
re
Required option. The name of the variable to be assigned to the regular expression pattern.
Pattern
Required option. Regular expression pattern to use. If syntax 1 is used, separate the mode with the "/" character. If syntax 2 is used, enclose the pattern in quotes.
Flags
Optional. If using syntax 2, enclose flags in quotes. Logo can be used in combination, and those available are:
g (Full text to find all patterns that appear)
i (Ignore case)
m (multiple line search)

Example

The following example creates an object (re) containing regular expression patterns and related flags to demonstrate how to use regular expression objects. In this example, the resulted regular expression object is used in the match method:

Copy the codeThe code is as follows:

function MatchDemo()
{
var r, re; // Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = new RegExp("ain","g"); // Create a regular expression object.
r = (re); // Find a match in the string s.
return(r);
}


If you still feel unsatisfied after reading the above content, please recommend it to everyone here30-minute tutorial on getting started with regular expressions, easier to get started and learn.