5 Easy, difficult, and impossible tasks

 

Some things are difficult or impossible with regular expressions, and many are elegant and highly expressive. The puzzles in this chapter ask you to think about which situation each puzzle describes.

Puzzle 18    Identifying equal counts

Summary

In this puzzle we would like to balance starting and ending symbols.

At times we encounter a message or a stream that uses balanced “increment” and “decrement” symbols. For example, one way to check that a message has terminated might be to match up the increments and decrements. The same concept would apply to many kinds of messages and symbols—perhaps you would like to set the table with the same number of forks and knives, for example.

As a simplification of the general problem, write a regular expression that matches strings that consist of any number of A characters, followed by the same number of B characters.

For example AAABBB and AAAAAAABBBBBBB should match, while AAAABBBBBB should fail to match.

ignore for audio

Author thoughts    Lateral thinking might help you find the answer

You cannot match patterns based on having an equal number of different symbols using regular expressions. Or at least you cannot do so in the general case. It is, of course, perfectly possible to require exactly seven A’s and exactly seven B’s. But if the count is arbitrarily large, the kind of “machine” that can match the message requires additional power.

AI thoughts    Hic sunt dracones

Puzzle 19    Matching before duplicate words

Author thoughts    Find a pattern that will fulfill the requirement

AI thoughts    Deep fakes in the Chomsky hierarchy

Puzzle 20    Testing an IPv4 address

Author thoughts    Ask whether regexen are powerful enough for a problem

AI thoughts    I want to be a machine

Puzzle 21    Matching a numeric sequence

Author thoughts    Rule out the impossible to be left with the solution

AI thoughts    Wheat and chessboards

Puzzle 22    Matching the Fibonacci sequence

Author thoughts    The Golden Spiral beautifully generalizes Fibonacci numbers

AI thoughts    The fractal geometry of nature