Zippie
Zippie

Reputation: 6088

What's the difference the two regular expression characters \b and \<

In the script I'm reading about regular expressions it says:

So what's the difference in using the following

Upvotes: 2

Views: 209

Answers (3)

A.H.
A.H.

Reputation: 66263

My man grep tells me about \b:

The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, [...]

So \bfoo\b would match wherever \<foo\> would match.

On the other hand: There are so many regexp variants, that it is hard to tell what yours is doing with \b.

Upvotes: 4

ikegami
ikegami

Reputation: 385897

Your source appears to be wrong, or at least incomplete. \b matches any border, not just the front one. Quote man grep:

The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word

  • grep's \b is equivalent to grep's \(\<\|\>\)

In case you are familiar with Perl regular expressions,

  • grep's \< is equivalent to Perl's (?<!\w)(?=\w)
  • grep's \> is equivalent to Perl's (?<=\w)(?!\w)
  • grep's \b is equivalent to Perl's \b
  • grep's \b is equivalent to Perl's (?:(?<!\w)(?=\w)|(?<=\w)(?!\w))

Upvotes: 3

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28005

\b is like \< and \> combined:

  • \< match at beginning of word,
  • \> match at end of word,
  • \b match at the begining OR end of word,
  • \B matches except at the beginning or end of a word.

Upvotes: 4

Related Questions