2

I am trying to learn Regular Expressions. I've looked at several tutorials but I did not find them clear or comprehensive. My questions is when is ^$ used and when is "\b ." used? I know what they mean but just are sure how.

Some examples:

1. \((\d+)\)\.\((\d+)\)\.\((\d+)\)
2. \b1?264[)- ]*\d{3}[- ]*\d{4}\b
3. ^[a-g]{4}$

Don't all Regular Expressions have to start with "^" and end with "$" ?

Concerned_Citizen
  • 6,548
  • 18
  • 57
  • 75
  • 1
    Read [Mastering Regular Expressions 3rd Edition](http://www.amazon.com/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124 "Best regex book ever"). Hands down the most useful book I've ever read. The time spent studying this quickly pays for itself many times over. – ridgerunner Aug 25 '12 at 03:14

1 Answers1

7

Before seeing when they are used, first you need to know what they mean:

  • ^ is a start of line anchor.
  • $ is an end-of-line of line anchor.
  • \b matches a word boundary. In other words, it matches between a word character \w and either a non-word character \W or the start or end of the string.

For example:

  • To check if a string starts with a digit use ^\d.
  • To check if a string ends with a digit use \d$.
  • To check if a string contains the word foo use \bfoo\b. Omitting the word boundaries would cause it to match words that contain foo such as seafood.
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • What do you mean "\b" matches between a word character \w and a non-word character \W ? – Concerned_Citizen Aug 25 '12 at 01:34
  • @GTyler: I have another answer where I explain \b and \B in more details: http://stackoverflow.com/questions/4541573/what-are-non-word-boundary-in-regex-b-compared-to-word-boundary Does that help? – Mark Byers Aug 25 '12 at 02:02
  • @Mark Byers: It's more correct to say that `\b` matches between a word character `\w` and not a word character because it can match at the start or end of a string if the first/last character is a word character. – MRAB Aug 26 '12 at 01:31