4 ms·
You can do that by building up a string and converting that to a regex. Pseudo-code: let day = "[0-9]{2}" let month = "jan|feb|…|dec" let year = "[0-9]{4
by Someone 4y ago
You can do that by building up a string and converting that to a regex. Pseudo-code:
let day = "[0-9]{2}"
let month = "jan|feb|…|dec"
let year = "[0-9]{4}"
let regex = Regex(month + " " + day + ", " + year)
Disadvantage is that, if your programming language has automatic syntax check of regular expressions, you probably lose that.
The string concatenations also make things a bit slower, but that almost always needs to be done only once.
Advantage is that this makes testing easier. For example, you can do
let dayRegex = Regex(day)
and then test that regex in isolation. That probably is overkill for this example, but if you change the regex to only accept numbers in [1,31], that can be useful.
If you decide to have your regex to treat 30-day and 31 day months separately, things get more complicated. I wouldn’t go that far, though, and certainly not as far as handling leap years correctly. When regexes get complex, it’s time to go for a proper lexer/parser.
- burntsushi 4y agoOf course I'm aware of that technique and I've used it many times. :-) Doesn't change what I said.
- ogogmad 4y agoSurely, you can use Rust's enums for this.
- burntsushi 4y agoAs I said above, I'm the author of Rust's regex crate. I know what Rust enums are. Still doesn't change what I said.
- ogogmad 4y agoI mean that it's typesafe.
- burntsushi 4y agoI still don't know what you're talking about. I didn't say anything about type safety? Nobody else did? I guess you're probably talking about a combinator API... Like this one: https://docs.rs/regex-syntax/latest/regex_syntax/hir/struct.Hir.html https://docs.rs/regex-syntax/latest/regex_syntax/hir/struct.... My original comment was talking about adding variables to the regex language itself. String interpolation and combinator APIs and enums and type safety are all beside the point. They surely solve a similar problem as regex variables in certain contexts, but they go about it in a very different way and are specific to the context in which the regex is created.