3 ms·
> my instinct is to reach for regexp captures, the solution it came up with is probably a lot faster and easier to read and avoids "now you have two problems”.
by textninja 4y ago
> my instinct is to reach for regexp captures, the solution it came up with is probably a lot faster and easier to read and avoids "now you have two problems”.
I don’t write Rust but I think it’s best to trust your instinct here. “Now you have two problems” is a humorous quip and not practical coding advice. Using a regular expression to strip trailing digits from a string will surely result in code that is shorter and more readable than the alternatives, and it will probably be more correct too.
- lamontcg 4y agoYou might be entirely correct. I noticed a small perf issue with the backwards scanning and had it rewrite it not using rfind("_"). First time I prompted it, though, it didn't actually manage to fix the problem and gave me some mild gaslighting until I told it to explicitly remove the rfind() call. Now I think the result should be comparable to or beat a regexp, but it is getting quite a bit more complex: fn strip_suffix(s: &str) -> String { let mut idx = s.len(); for (i, c) in s.char_indices().rev() { if c == '_' { idx = i; break; } else if !c.is_ascii_digit() { return s.to_string(); } } if idx == s.len() { return s.to_string(); } if s[idx+1..].chars().all(|c| c.is_ascii_digit()) { return s[..idx].to_string(); } s.to_string() } .char_indexes().rev() there worries me a bit as well now that I look at it... haven't tested that at all.
- lamontcg 4y agoAh, it looks like char_indexes() implements DoubleEndedIterator and you can only call rev() on an iterator that does implement it, so that's fine.
- textninja 4y agoIt took some coaching to get it to use the terse style I prefer, but here’s what 3.5 came up with in a conversation where I first asked about Rust’s support for regular expressions: use regex::Regex; fn strip_suffix_digits(s: &str) -> &str { let re = Regex::new(r"_\d+$").unwrap(); re.replace(s, "").as_ref() } As someone who does not program in Rust I find that quite readable, though I haven’t run it and can’t comment on how it compares outside of LOC. It does depend on the regex crate though.
- lamontcg 4y agoYeah I got basically the same sort of result out of it by asking for a Regexp, much shorter.