Logo

Programming-Idioms

  • Clojure
  • Python

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 re
m = re.search(r'\b\d\d\d\b', s)
x = m.group(0) if m else ''
#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