3 ms·
I'll use this as an opportunity to plug the regex crate's new 'extract' API. :-) use regex::Regex; fn main() { println!("{:?}", extract("1973-
by burntsushi 3y ago
I'll use this as an opportunity to plug the regex crate's new 'extract' API. :-)
use regex::Regex;
fn main() {
println!("{:?}", extract("1973-01-05 09:30:00"));
}
fn extract(haystack: &str) -> Option<(&str, &str, &str, &str, &str, &str)> {
let re = Regex::new(
r"([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})",
).unwrap();
let (_, [y, m, d, h, min, s]) = re.captures(haystack)?.extract();
Some((y, m, d, h, min, s))
}
Output:
Some(("1973", "01", "05", "09", "30", "00"))
That gets you pretty close to what you want here.
(The regex matches more than what is a valid date/time of course.)
- Izkata 3y agoPython (even in 2): >>> import re >>> pattern = re.compile(r"([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})") >>> results = pattern.match('1973-01-05 09:30:00') >>> results.groups() ('1973', '01', '05', '09', '30', '00') >>> (y, m, d, h, min, s) = results.groups() (`results` will be None if the regex didn't match) Regexes are one of those things where, once you understand it (and capture groups in particular) and it's available in the language you're working in, string-splitting usually doesn't feel right anymore.
- burntsushi 3y agoI believe all of the people in this thread understand regexes extremely well. :-) There is a lot of reasonable room to disagree about when and where regexes should be used.