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

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?

Correct me if am wrong!

Answers:

Answer

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" /;$\n\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!

Answer

^ represents the start of the input string.

$ represents the end.

You don't actually have to use them at the start and end. You can use em anywhere =) Regex is fun (and confusing). They don't represent a character. They represent the start and end.

This is a very good website

Answer

They match the start of the string (^) and end of the string ('$').

You should use them when matching strings at the start or end of the string. I wouldn't say you have to use them, however.

Answer

^ anchors the beginning of the RE at the start of the test string, and $ anchors the end of the RE at the end of the test string. If that's what you want, go for it! However, if you're using REs of the form ^.*theRealRE.*$ then you might want to consider dropping the anchors and just using the core of the RE on its own.

Some languages force REs to be anchored at both ends by default.

Answer

I have tested these.
1. /^a/ matches abb, ab but not ba, bab, bba.
2. /a/ matches abb, ab and ba, bab, bba.

I think that /^a/ matches such strings starting a.
/a/ matches such strings contains a.

Similar to /^a/, /a$/ matches ba, a, but not ab, bab.

Refer http://www.regular-expressions.info/anchors.html .


If you notify wrong(or strange) sentence in above or this to me, I would thank you.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.