Go (RE2)

Word Boundary (Whole Word Match) in GO

Match the whole word `cat` without matching it inside other words like `concatenate` or `category`.

Try it in the GO tester →

Pattern

regexGO
\bcat\b   (flags: gi)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?i)\bcat\b`)
	input := `The cat sat on the mat.`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

\b is a zero-width assertion at a word boundary — the position between a word character (\w) and a non-word character (or string edge). Wrapping `cat` in two \b anchors forces the match to start AND end at word boundaries, so `cat` matches but `concat` and `cats` do not.

Examples

Input

The cat sat on the mat.

Matches

  • cat

Input

I will concatenate the strings.

No match

Input

CAT, Cat, cat — all match.

Matches

  • CAT
  • Cat
  • cat

Same pattern, other engines

← Back to Word Boundary (Whole Word Match) overview (all engines)