Logo

Programming-Idioms

  • C++
  • 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.

using System.Text.RegularExpressions;
var re = new Regex(@"\b\d\d\d\b");
string x = re.Match(s).Value;

The Regex constructor can take additional options.

Call Matches() to find all matches.
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.
#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()
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.

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