且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式中的脱字号(^)和美元符号($)有什么需求?

更新时间:2023-02-22 13:49:21

JavaScript RegExp()允许您指定多行模式(m),该模式可更改^$的行为.

Javascript RegExp() allows you to specify a multi-line mode (m) which changes the behavior of ^ and $.

^表示多行模式下当前行的开头,否则为字符串的开头

^ represents the start of the current line in multi-line mode, otherwise the start of the string

$表示多行模式下当前行的结尾,否则为字符串的结尾

$ represents the end of the current line in multi-line mode, otherwise the end of the string

例如:这使您可以在行的末尾匹配分号之类,下一行以"var" /;$\n\s*var/m

For example: this allows you to match something like semicolons at the end of a line where the next line starts with "var" /;$\n\s*var/m

快速regexen也需要一个锚点",在某个地方开始在字符串中的某个地方进行搜索.这些字符告诉Regex引擎从哪里开始寻找,并通常减少回溯的次数,从而使Regex在许多情况下快得多.

Fast regexen also need an "anchor" point, somewhere to start it's search somewhere in the string. These characters tell the Regex engine where to start looking and generally reduce the number of backtracks, making your Regex much, much faster in many cases.

注意:此知识来自Nicolas Zakas的高性能Javascript

NOTE: This knowledge came from Nicolas Zakas's High Performance Javascript

结论:您应该使用它们!