Logo

Programming-Idioms

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

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.

#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()
using System.Text.RegularExpressions;
string x = Regex.Match(s, @"\b\d\d\d\b").Value;

Construct a Regex instance (possibly compiled) if using the same pattern many times.

Call Matches() to find all matches.

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