This language bar is your friend. Select your favorite languages!
Select your favorite languages :
  • Or search :

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.

#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] : '';
uses RegExpr;
  with TRegExpr.Create do
    Expression := '\b\d\d\d\b';
    x := Match[0];
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...
< >