Ant's
Ant's

Reputation: 13811

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?

Upvotes: 50

Views: 76115

Answers (5)

조영하
조영하

Reputation: 41

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.

Upvotes: 4

Eric Wendelin
Eric Wendelin

Reputation: 44349

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!

Upvotes: 41

Donal Fellows
Donal Fellows

Reputation: 137567

^ 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.

Upvotes: 2

Oded
Oded

Reputation: 498982

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.

Upvotes: 5

Rudie
Rudie

Reputation: 53821

^ 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

Upvotes: 13

Related Questions