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

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

问题描述

我最近读过有关Java Script正则表达式的内容,但我感到困惑。

我的作者说必须包含插入符号( ^ )和美元符号( $ )?为什么实际需要这个?它的目的是什么?

I have read recently about Java Script regular expressions, but i have got confused.
My author says that it is must to include the caret (^) and dollar symbol ($) at the beginning and end of the all regular expressions declarations? Why this is needed actually? Whats its purpose?

如果错了,请纠正我!

推荐答案

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 \ * * 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

结论:你应该使用它们!

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

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