Logo

Programming-Idioms

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

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 static java.util.regex.Pattern.compile;
import java.util.regex.Matcher;
Matcher m = compile("\\b\\d{3}\\b").matcher(s);
String x = m.find() ? m.group() : "";
#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