Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - What is the need for caret (^) and dollar symbol ($) in regular expression?

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.

Why are they needed?

question from:https://stackoverflow.com/questions/5921699/what-is-the-need-for-caret-and-dollar-symbol-in-regular-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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

Conclusion: You should use them!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...