Logo

Programming-Idioms

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

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.

const matches = s.match(/\b\d{3}\b/);
const x = matches ? matches[0] : '';
#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();
using System.Text.RegularExpressions;
string x = Regex.Match(s, @"\b\d\d\d\b").Value;
using System.Text.RegularExpressions;
var re = new Regex(@"\b\d\d\d\b");
string x = re.Match(s).Value;
import "regexp"
re := regexp.MustCompile(`\b\d\d\d\b`)
x := re.FindString(s)
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() : "";
uses RegExpr;
  with TRegExpr.Create do
  begin
    Expression := '\b\d\d\d\b';
    Exec(s);
    x := Match[0];
    Free;
  end;
my ($x) = $s =~ /\b(\d{3})\b/;
import re
m = re.search(r'\b\d\d\d\b', s)
x = m.group(0) if m else ''
x = s.match(/\b\d{3}\b/).to_s
use regex::Regex;
let re = Regex::new(r"\b\d\d\d\b").expect("failed to compile regex");
let x = re.find(s).map(|x| x.as_str()).unwrap_or("");

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