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.

using System.Text.RegularExpressions;
var re = new Regex(@"\b\d\d\d\b");
string x = re.Match(s).Value;
using System.Text.RegularExpressions;
string x = Regex.Match(s, @"\b\d\d\d\b").Value;
#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();
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("");

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