Home Web Front-end JS Tutorial The meaning and use of regular expressions in JavaScript

The meaning and use of regular expressions in JavaScript

Nov 09, 2017 pm 04:52 PM
javascript js expression

I believe that many people know regular expressions, but many people’s first impression is that it is difficult to learn, because at first glance, they feel that there is no pattern at all, and it is all a bunch of various All kinds of special symbols are completely incomprehensible. In fact, regular expressions are not as difficult as you think. Today we will take you to quickly understand JavaScriptregular expressions!

1. What is a regular expression?

Regular expression is a special The string pattern is used to match a set of strings, which is like using a mold to make a product, and regular rules are this mold, defining a rule to match characters that match the rules.

Regular expression (regular expression) describes a string matching pattern (pattern), which can be used to check whether a string contains a certain substring, replace the matching substring, or select from a certain string. Get substrings that meet certain conditions, etc.

To put it bluntly, regular expressions are used to process strings. We can use it to process some complex strings.

2. Regular expression rules

##1.1 Ordinary characters

Letters, numbers, Chinese characters, underscores, and punctuation marks not specifically defined in the following chapters are all "ordinary characters". Ordinary characters in an expression, when matching a string, match the same character.


Example 1: The expression "c", when matching the string "abcde", the matching result is: success; the matched content is: "c"; the matched position is: starting at 2, Ended at 3. (Note: Whether the subscript starts from 0 or 1 may differ depending on the current
programming language)
Example 2: The expression "bcd" matches the string "abcde" ", the matching result is: success; the matched content is: "bcd"; the matched position is: starting at 1 and ending at 4.

3. Special characters in regular expressions

Character meaning

\ is used as a change of meaning, that is, the characters after "\" are usually not interpreted according to their original meaning. For example, /b/ matches the character "b". When a backslash is added in front of b, /\b/ will change the meaning. To match a word boundary.
-or-
Restoration of regular expression functional characters, such as "*" matching the metacharacter before it 0 or more times, /a*/ will match a, aa, aaa, with "\" added After that, /a\*/ will only match "a*".

^ matches an input or the beginning of a line, /^a/ matches "an A", but does not match "An a"
$ matches an input or the end of a line, /a$/ matches " An a", not matching "an A"
* Matches the preceding metacharacter 0 or more times, /ba*/ will match b,ba,baa,baaa
+ Matches the preceding metacharacter 1 or more times times, /ba*/ will match ba,baa,baaa
? Match the preceding metacharacter 0 or 1 times, /ba*/ will match b,ba
(x) Match x and save x in a file named $1 ...in the variable of $9
x|y matches x or y
{n} matches exactly n times
{n,} matches n or more times
{n,m} matches n-m times
[xyz] character set, matches any character (or metacharacter) in this set
[^xyz] does not match any character in this set
[\b] Matches a backspace character
\b Matches a word boundary
\B Matches a non-word boundary
\cX Here, X is a control character, /\cM/ matches Ctrl-M
\d matches an alphanumeric character, /\d/ = /[0-9]/
\D matches a non-alphanumeric character, /\D/ = /[^0-9]/
\n matches a Line feed character
\r matches a carriage return character
\s matches a blank character, including \n,\r,\f,\t,\v, etc.
\S matches a non-blank character, equal to /[^\n\f\r\t\v]/
\t Matches a tab character
\v Matches a double tab character
\w Matches a character that can form a word ( alphanumeric, this is my free translation, including numbers), including underscores, such as [\w] matches the 5 in "$5.98", which is equal to [a-zA-Z0-9]
\W matches a word that cannot be formed Characters, such as [\W] matches the $ in "$5.98", which is equal to [^a-zA-Z0-9].

4. Basic syntax of regular expressions

Two special symbols '^' and ' $'. Their function is to indicate the beginning and end of a string respectively.

Examples are as follows:

"^The": represents all strings starting with "The" ("There", "The cat", etc.);

"of despair$": indicates a string ending with "of despair";

"^abc$": indicates a string starting and ending with "abc" - haha, there is only "abc" itself. ;

"notice": Represents any string containing "notice".

Like the last example, if you don't use two special characters, you are indicating that the string you want to find is in any part of the searched string - you are not
positioning it at the top of a certain .

Other symbols include '*', '+' and '?', which represent the number of times a character or a sequence of characters appears repeatedly.

They mean "none or more", "once or more" and "none or once" respectively.

Here are a few examples:

"ab*": Indicates that a string has an a followed by zero or several b. ("a", "ab", "abbb",...);

"ab+": Indicates that a string has an a followed by at least one b or more;

" ab?": Indicates that a string has an a followed by zero or one b;

"a?b+$": Indicates that there is zero or one a followed by one or several b at the end of the string .

You can also use a range, enclosed in curly brackets, to indicate the range of repetitions.

"ab{2}": Indicates that a string has an a followed by 2 b ("abb");

"ab{2,}": Indicates that a string has a a followed by at least 2 b;

"ab{3,5}": Indicates that a string has an a followed by 3 to 5 b.

Please note that you must specify the lower limit of the range (eg: "{0,2}" instead of "{,2}").

Also, you may have noticed that '*', '+' and '?' are equivalent to "{0,}", "{1,}" and "{0,1}".

There is also a '¦', which means "or" operation:

"hi¦hello": indicates that there is "hi" or "hello" in a string;

"(b¦cd)ef": represents "bef" or "cdef";

"(a¦b)*c": represents a string of mixed "a" and "b" followed by A "c";

'.' can replace any character:

"a.[0-9]": Indicates that a string has an "a" followed by an arbitrary character and A number;

"^.{3}$": represents a string of any three characters (length is 3 characters);

Square brackets indicate that certain characters are allowed to appear at a specific position in a string:

"[ab]": Indicates that a string has an "a" or "b" (equivalent to "a¦b");

"[a-d]": Indicates that a string contains one of lowercase 'a' to 'd' (equivalent to "a¦b¦c¦d" or " [abcd]");

"^[a-zA-Z]": represents a string starting with a letter;

"[0-9]%": represents a hundred There is one digit before the semicolon;

",[a-zA-Z0-9]$": indicates that a string ends with a comma followed by a letter or number.

You can also use '^' in square brackets to indicate unwanted characters. '^' should be the first one in the square brackets.

(For example: "%[^a-zA-Z]%" means that letters should not appear between two percent signs).

In order to express verbatim, you must add the transfer character '\' before the characters "^.$()¦*+?{\".

Please note that within square brackets, no escape characters are required.

Summary

In fact, I just don’t understand regular expressions, so I understand. You will find that this is it. There are not many related characters used in regular expressions, and they are not difficult to remember or understand. The only difficulty is that after combining them, the readability is relatively poor and it is not easy to understand. This article It is designed to let everyone have a basic understanding of regular expressions, be able to understand simple regular expressions, and write simple regular expressions to meet the needs of daily development.

Related recommendations:

What are the commonly used regular expressions in js

JavaScript regular expression video tutorial

Definition and introduction of javascript regular expression

How to be flexibleUse JavaScriptRegular expression

The above is the detailed content of The meaning and use of regular expressions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles