Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regular Expression – Metacharacters \b and \B

Regular Expression - Metacharacters \b and \B

Regular expressions - metacharacters Regular Expression - Metacharacters

\b and \B are two special metacharacters in regular expressions used to match word boundaries.


Word Boundary \b

In regular expressions, \b is a special metacharacter that denotes a word boundary. It matches the position at the start or end of a word, without matching any actual character.

Specifically, \b matches one of the following three cases:

The following are some metacharacter \b examples:

Note that the\b is a zero-width assertion that does not match an actual character but only a position. Therefore, when you want to match an actual character, do not use \b; instead, use other characters or character combinations.

Example

// Use \b for word matching

var

patternWord

=

/\bword\b/

;

var

textWord

=

'This is a word in a sentence.'

;

if

(

patternWord.

test

(

textWord

)

)

{

    document.

write

(

'Found matching word:'

,

patternWord.

exec

(

textWord

)

[

0

]

)

;

}

else

{

    document.

write

(

'No matching content found!'

)

;

}

Try it »


Non-word Boundary \B

In regular expressions, \B is \b the opposite symbol of \b, representing a non-word boundary, that is, a position that is not at a word boundary.

Specifically,\B \B matches one of the following cases:

The following are some metacharacter \B examples:

Note that, unlike \b , \B is also a zero-width assertion that matches only positions and not actual characters.

Example

// Use \B for non-word matching

var

patternWord

=

/\Bword\B/

;

       

// This one is found

var

textWord

=

'This is a password123 in a sentence.'

;

       

// This one is not found

//var textWord = 'This is a password in a sentence.';

if

(

patternWord.

test

(

textWord

)

)

{

    document.

write

(

'Found matching word:'

,

patternWord.

exec

(

textWord

)

[

0

]

)

;

}

else

{

    document.

write

(

'No matching content found!'

)

;

}

Try it »

Regular expressions - metacharacters Regular Expression - Metacharacters