Logo

Programming-Idioms

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.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#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)
const matches = s.match(/\b\d{3}\b/);
const x = matches ? matches[0] : '';
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Pattern pattern = Pattern.compile("((?<!\\d)\\d{3}(?!\\d))");
Matcher matcher = pattern.matcher(s);
String x = "";
matcher.find();
x = matcher.group(1);
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("");