Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #239 Find first regular expression match

Assign to string x the first word of string s consisting of exactly 3 digits, or the empty string if no such match exists.

A word containing more digits, or 3 digits as a substring fragment, must not match.

import "regexp"
re := regexp.MustCompile(`\b\d\d\d\b`)
x := re.FindString(s)

re may (and should) be reused.
\b matches word boundaries.
\d matches a single digit.
#include <regex>
std::regex re("\\b\\d{3}\\b");
auto it = std::sregex_iterator(s.begin(), s.end(), re);
std::string x = it == std::sregex_iterator() ? "" : it->str();

Can call ++it to find successive matches, until it == std::sregex_iterator()

New implementation...
< >
programming-idioms.org