JavaScript regular expression

Posted by oolongdavies on Thu, 10 Mar 2022 05:46:48 +0100

Introduction to regular expressions

Definition: regular expressions are used to define the rules of some strings.

Function: the computer can check whether a string conforms to the specified rules according to the regular expression; Or extract the content that conforms to the rules in the string.

Create regular expression objects

Method 1: use constructor to create regular expression object

Syntax:

	var variable = new RegExp("regular expression "); // Note that the parameter is a string

	var variable = new RegExp("regular expression ", "Matching pattern"); // Note that both parameters are strings

Note: regexpress means Regular expression. Using typeof to check regular objects will return object.

In the above syntax, you can pass either one parameter or two parameters.

How to use the regular expression object after it is created? It is roughly divided into two steps:

  • (1) Create regular expression object reg.

  • (2) Use the test() method of reg to judge whether the specified string conforms to the rules.

test() method of regular expression: [important]

	myReg.test(str); // Judge whether the string str conforms to the rule of the specified myReg regular expression

Explanation: the test() method can be used to check whether a string conforms to the rules of regular expressions. If so, it returns true, otherwise it returns false.

Let's take a look at the following example.

1. When transmitting a parameter:

In the constructor RegExp, you can pass only one parameter.

Code example:

	var reg = new RegExp("x"); // Check whether a regular expression contains a string

	var str1 = "ximingx";
	var str2 = "bawd";

	// Use the test() method to judge whether the string conforms to the reg rules defined above
	console.log(reg.test(str1)); // Print result: true
	console.log(reg.test(str2)); // Print result: false

Note that in the above example, we first define a regular expression rule, and then use the test() method of the regular expression to judge whether the string conforms to the previously defined rule.

2. When two parameters are passed: matching mode [important]

In the constructor RegExp, you can also pass two parameters. We can pass a matching pattern as the second parameter. This parameter can be:

  • i ignore case. i here refers to ignore.

  • g global matching pattern. g here refers to global.

Code example:

    var reg = new RegExp('M', 'i');
    var str = 'ximingx';

    console.log(reg.test(str)); // Print result: true

Method 2: create regular expressions with literal values

We can use literals to create regular expressions.

Syntax:

	var variable = /regular expression /;  

	var variable = /regular expression /Matching pattern;  // Note that there are no quotation marks in this syntax

Example code:

	var reg = /X/i; // Rules for defining regular expressions: check whether a string contains a. Ignore case.
	var str = "ximingx";

	console.log(typeof reg);  // Print result: object
	console.log(reg.test(str)); // Print result: true

Comparison of the above two methods

  • Method 1: it is more flexible when using the constructor, because variables can also be passed in the parameters.

  • Method 2: it is easier to create by using literal quantity.

Code example:

	var reg = new RegExp("a", "i"); // Mode 1

	var reg = /a/i; // Mode 2

The above two lines of code are equivalent.

Pit avoidance Guide: global matching g, use test() method with caution

For regular expressions that are not globally matched, test() will only detect whether there is a target string (true as long as it exists), and the results of multiple detection are the same. For example:

const reg = /test/;
const str = '_test_test';

reg.test(str) // true
reg.test(str) // true
reg.test(str) // true

Here's the point.

When the global flag / g is set, once there is still a match in the string, the test() method will return true. At the same time, after the match is successful, the value of lastIndex attribute will be set to the position of the first character after the last successful match result, and the next match will start from the position indicated by lastIndex; false is returned when the matching is unsuccessful, and the value of lastIndex property is reset to 0.

const reg = /test/g;
const str = '_test_test_test';

console.log(reg.test(str)); // true
console.log(reg.lastIndex); // 5

console.log(reg.test(str)); // true
console.log(reg.lastIndex); // 10

console.log(reg.test(str)); // true
console.log(reg.lastIndex); // 15

console.log(reg.test(str)); // false
console.log(reg.lastIndex); // 0

Summary:

The global matching pattern g is generally used for methods such as exec(), match(), replace().

The global matching pattern g is problematic if it is used in the test() method. Because the g pattern will generate a lastindex parameter to store the location of the last match.

Simple syntax of regular expressions

Check whether a string contains a or b

Writing method 1:

	var reg = /a|b/;

Explain: use | to express or.

Writing method 2:

	var reg = /[ab]/;  // It is equivalent to the above line of grammar

Explanation: the [] here also means or.

[] is commonly used in regular. Let's look at a few examples.

[] means: or

Some rules:

  • /[ab] / equivalent to / a|b /: check whether a string contains a or B

  • /[a-z] /: check whether a string contains any lowercase letters

  • /[A-Z] /: any capital letter

  • /[A-z] /: any letter

  • /[0-9] /: any number

  • /a[bde]c /: check whether a string contains abc or adc or aec

[^] means: except

Example 1:

  var reg = /[^ab]/; // Rule: are there any other characters in the string except a and b?
  var str = "acb";

  console.log(reg.test(str)); // Print result: true

Example 2: (it can be used to verify whether a string is a pure number)

	var reg = /[^0-9]/;  // Rule: is there anything else in the string other than numbers?
	var str1 = "1991";
	var str2 = "199a1";

	console.log(reg.test(str1)); // Print result: false (if the string is a pure number, false will be returned)
	console.log(reg.test(str2)); // Print result: true

Method of String object supporting regular expression

The following methods of String objects support regular expressions:

methoddescriberemarks
split()Splitting strings into arrays
search()Whether the search string contains the specified content and returns the index
match()According to the regular expression, the qualified content is extracted from a string
replace()Replace the specified content in the string with new content and return

Here are the introduction and examples.

split()

split(): splits a string into an array. You can accept a regular expression as an argument.

Regular related examples: according to any letter, the string is divided into an array.

Code implementation: (through regular)

	var str = "1a2b3c4d5e6f7g";

	var result = str.split(/[A-z]/); // Parameter is a regular expression: represents all letters
	console.log(result);

Print results:

	["1", "2", "3", "4", "5", "6", "7", ""]

search()

search(): whether the search string contains the specified content. If the specified content is searched, the index that appears for the first time will be returned; Otherwise, - 1 is returned.

The search() method can accept a regular expression as a parameter, and then retrieve the string according to the regular expression. serach() only looks for the first one, and it's no use even setting up a global match.

give an example:

	var str = "hello abc hello aec afc";
	/*
	* Whether the search string contains abc or aec or afc
	*/
	result = str.search(/a[bef]c/);
	console.log(result); // Print result: 6

match()

match(): according to the regular expression, extract the qualified content from a string, encapsulate it into an array and return it (even if only one result is queried).

Note: by default, the match() method will only find the first content that meets the requirements, and stop searching after finding it. We can set the regular expression to the global matching mode, so that all contents will be matched and returned in the form of array.

In addition, we can set multiple matching patterns for a regular expression, and the order of matching patterns doesn't matter.

Code example:

	var str = "1a2a3a4a5e6f7A8B9C";

	var result1 = str.match(/[a-z]/);   // Find the first content that meets the requirements, and then return
	var result2 = str.match(/[a-z]/g);  // Set to "global match" mode to match all lowercase letters in the string
	var result3 = str.match(/[a-z]/gi); // Set multiple matching patterns to match all letters in the string (ignoring case)

	console.log(result1); // Print result: [a]
	console.log(result2); // Print result: [a "," a "," a "," a "," e "," F "]
	console.log(result3); // Print results: [a "," a "," a "," a "," e "," F "," a "," B "," C "]

Summary:

match() is a very practical method, which can extract regular content from a long string. Isn't this the scene often encountered by reptiles?

replace()

replace(): replace the specified content in the string with new content and return. The original string will not be modified.

Syntax:

	New string = str.replace(Replaced content, new content);

Parameter interpretation:

  • Replaced content: a regular expression can be accepted as a parameter.

  • New content: only the first one will be replaced by default. If you need to replace all the qualified contents, you can set the regular expression to the global matching mode.

Code example:

    //replace() method: replace
    var str2 = "Today is fine day,today is fine day !!!"

    console.log(str2);
    console.log(str2.replace("today","tomorrow"));  //Only the first today can be replaced
    console.log(str2.replace(/today/gi,"tomorrow")); //Here we use regular and "global matching" mode to replace all today

Examples of common regular expressions

Check whether a string is a legal mobile phone number

Rules for mobile phone numbers:

  • Start with 1 (^ 1 starts with 1, [^ 1] is not 1 or except 1)

  • The second digit is any number between 3 and 9

  • Any 9 digits after three digits

Regular implementation:

	var phoneStr = "13067890123";

	var phoneReg = /^1[3-9][0-9]{9}$/;

	console.log(phoneReg.test(phoneStr));

Note: if both ^ and $symbols are used in a regular expression, the string must fully conform to the regular expression.

Remove the spaces at the beginning and end of the string

Regular implementation:

	str = str.replace(/^\s*|\s*$/g,"");

The explanation is as follows:

	str = str.replace(/^\s*/, ""); //Remove leading spaces

	str = str.replace(/\s*$/, ""); //Remove trailing spaces

Determine whether the string is email

Regular implementation:

	var emailReg = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;

	var email = "abchello@163.com";

	console.log(emailReg.test(email));

Topics: Javascript Front-end regex