regexp-examples
regexp-examples copied to clipboard
enhancement: negative examples?
Is there a way to generate counter-examples to a regex pattern? This would be incredibly useful for writing tests for format validators. Think validates_format_of
for shoulda-matchers.
Conceptually, it would enumerate all strings that don't match the pattern.
Ideal behavior:
/a+/.counter_examples #=> ["", "b", "c", "d", ...]
/hello/.counter_examples #=> ["", "a", "b", "c", ...]
/.*/.counter_examples #=> [] (or nil)
it seems like this is computationally possible at least. the complement of a regular language is also regular, which means that you can enumerate the counter-examples by "negating" the regular expression's deterministic finite automaton representation, and then enumerating examples from that.
https://math.stackexchange.com/questions/685182/complement-of-a-regular-expression
I like the idea, but I suppose this problem should be solved be a separate gem - what do you think?
For example, we could have RegexpNegator.new(regex) #=> negated_regex
Or even, if the problem is feasibly doable, this could be a core ruby method - e.g. Regexp#negate
? In which case, this gem could be used as follows:
/hello/.negate.random_example
...But what does a negated /hello/
actually look like? Without using irregular aspects of regex (i.e. look-arounds), that is. I suspect this may closely relate to this problem I encountered with the absence operator.
Edit -- See also: https://bugs.ruby-lang.org/issues/5588