Home Web Front-end JS Tutorial Detailed explanation of JS regular single-line mode

Detailed explanation of JS regular single-line mode

Mar 29, 2018 pm 04:15 PM
javascript model Detailed explanation

This time I will bring you a detailed explanation of the JS regular single-line mode. What are the precautions when using the JS regular single-line mode. The following is a practical case, let's take a look.

Regular Expression was first implemented by Ken Thompson in his improved QED editor in 1970. The simplest metacharacter in the regular expression "." matched at that time is any character except line breaks:

"." is a regular expression which matches any character except .

The above sentence comes from the official document of QED in 1970 , which may be the first regular document in history.

Why is this stipulated? This is because QED edits files in line units, and the newline character at the end of the line is also included in the content of this line. For example, if you want to delete all single-line comments in a piece of code, you can use the following command in QED:

1,$s#//.*##
Copy after login

If "." can match the newline character, then the newline character will also be deleted, and it will Causes these lines to be merged with the next line, which is usually not what we want. Therefore, "." was designed not to match newlines when it was originally invented. Although there is no QED command on the current operating system for us to test, we still have VIM, and the "." in VIM cannot match the newline character for the same reason.

Unlike in Node, reading filesusually reads the entire file in one go, Perl inherits the tradition of many Linux commands reading files line by line, like this:

while (<>) {print $_}
Copy after login
There is also a newline character at the end of

_, so Perl naturally inherits QED's rule that "." does not match newline characters. But Perl is a programming language after all, not an editor. The objects that its regular expressions need to match are not only single lines of text, but also multi-line text. Therefore, in its regular expressions, "." There is a need for cross-line matching, so Perl invented the regular single-line mode /s, which allows "." to also match newline characters. The official description of the /s modifier in Perl used to turn on single line mode is "Treat the string as single line". This "single line" should be understood like this: "." can only match in normal mode. Inline characters cannot span lines; in single-line mode, Perl will pretend to treat multi-line strings as one line, and treat the newline characters as inline characters, so "." can match them. To put it more vividly, the following three lines of text

1
2
3
Copy after login

are regarded as "1\n2\n3\n" one line of text. This is what single-line mode means.

But the terrible thing is that for the same reason (string variables can contain multiple lines of text), Perl also invented the /m modifier, which is multi-line mode. The official description is "Treat the string as multiple lines ", this pattern has been included in the regular rules of

JavaScript

since ancient times. The "multiple lines" here means: ^ and $ metacharacters will not match the positions before and after the newline characters in the middle of a string by default, that is It is believed that the string will always have only one line, and it can be matched after turning on the multi-line mode. In other words, single-line mode and multi-line mode are for different metacharacters. People who are new to regular expressions will be confused by the two seemingly corresponding "single-line mode" and "multi-line mode". concept, but in fact, it is confusing with unrelated terms.

Later, the author of Ruby may have felt that the regular term "single-line mode" was not used well, so he called the pattern of "." matching newlines "multi-line mode", that is, let . * and other regular expressions can match multiple lines, so it makes perfect sense. The modifier also uses /m (Ruby will enable the "multiline mode" in Perl by default, so /m is not occupied). This is really To add insult to injury, it’s even more chaotic.

Later, the Python author may also feel that the term "single-line mode" should be avoided, so he gave a new name "dotall", which means that dot can match all characters. It is a good name. , and later Java also used this name.

上面回顾了一下历史,解释了下单行模式的由来以及说明了下单行模式这个名字起得不好。V8 最近刚刚实现了一个 stage 3 的 ES 提案 https://github.com/mathiasbynens/es-regexp-dotall-flag,这个提案为 JavaScript 的正则引入了 /s 修饰符和 dotAll 属性,dotAll 属性是学了 Python 和 Java,/s 修饰符是继承了 Perl 的,这里也没必要发明一个新的修饰符比如 /d,只会让事情更复杂。/s 在 JavaScript 的具体效果是让 “.” 能匹配以前不能匹配的四个行终止符:\n(换行)、\r(回车)、\u2028(行分隔符)、\u2029(段落分隔符):

/foo/s.dotAll // true
/^.{4}$/s.test("\n\r\u2028\u2029") // true
Copy after login

其实就是个很简单的东西,但可能一些没有接触过 JavaScript 以外的正则的同学到时候学到这个新的模式后会产生困惑,这里再澄清一下:多行模式控制的是 ^ 和 $ 的表现,单行模式控制的是 “.” 的表现,两者没有直接关系。

然而当初引入单行模式和多行模式这两个易混淆概念的 Perl 语言,已经在 Perl 6 中完全删除了这两个模式:“.” 号默认就匹配换行符,\N 可以匹配换行符除外的任意字符;^ 和 $ 始终匹配字符串的首尾,而新引入了 ^^ 和 $$ 两个元字符来匹配行的首尾。

过去我们常用的单行模式的替代品 [^] 或者 [\s\S] 也不是完全没有用了,比如在一些使用 JavaScript 正则的编辑器里(VS Code、Atom),不太可能给你提供开启单行模式的界面。不过说起编辑器里的正则功能,用 JavaScript 实现的编辑器的正则功能还是太弱了,比如不能在正则自身内部开启某些模式,比如要是在 Sublime(使用 Python 正则)里的话,在正则内部使用 (?s) 就能开启 dotall 模式,比如可以用 (?s)/\*.+?\*/ 匹配到所有的多行注释。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

在正则中怎么使用环视

正则表达式怎么匹配图片地址与img标签

The above is the detailed content of Detailed explanation of JS regular single-line mode. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Should I shut down my laptop every time? Should I shut down my laptop every time? Feb 19, 2024 pm 12:09 PM

Windows laptops come with hibernation and shutdown options. When you put your laptop into sleep mode, it enters a low-power mode and you can continue working in any way you left it. If you shut down your laptop, you need to close all programs and your work and start over. If you want to take a break from your laptop throughout the day, sleep mode or hibernation mode is a good option. What about closing the door? Should I shut down my laptop every time? Let's find out. Should I shut down my laptop every time? It may be a good idea to turn off your laptop to save energy and extend the life of the device, especially if it is not used for an extended period of time. But during the day, it’s a good idea to put your laptop into sleep mode to continue your tasks

See all articles