正则表达式中的脱字号(^)和美元符号($)有什么需求? [英] What is the need for caret (^) and dollar symbol ($) in regular expression?

查看:112
本文介绍了正则表达式中的脱字号(^)和美元符号($)有什么需求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读过有关JavaScript正则表达式的信息,但我感到困惑.

I have read recently about JavaScript regular expressions, but I am confused.

作者说,有必要在所有正则表达式声明的开头和结尾都包括脱字符号(^)和美元符号($).

The author says that it is necessary to include the caret (^) and dollar symbol ($) at the beginning and end of the all regular expressions declarations.

为什么需要它们?

推荐答案

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

结论:您应该使用它们!

这篇关于正则表达式中的脱字号(^)和美元符号($)有什么需求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆