Sunday, 19 October 2014

Regex Golf on regex.alf.nu - Part 1

If you haven't already, go here: http://regex.alf.nu/0

The first one needs you to match words with 'foo' in them, so the solution is straightforward.

foo

The second one has all words that end in 'k'. We use `k` followed by the end of line anchor `$`.

k$

Number 3, Ranges requires you to match all words that contain characters from a to f only.

^[a-f]+$

Backrefs is where it gets interesting. We need to match words that repeat a sequence of characters, like allochirally, heavyheaded or barbary.

(\w{3})\w*\1

Here we match any letter thrice in a group, followed by 0 or more letters followed by our first group. The 0 or more is important in cases like barbary where there is no letter between the group and its repetition.

I had to handle an edge case in Abba, but it looks alright otherwise. The level description is suggestive of a simpler solution but I couldn't figure that out.

^(?:[en](?!n)\w+|(?:(\w)(?!\1))+)$

Visual representation from Debuggex helps a lot in case of complicated regular expressions.



The edge case is for effusive and noisefully.

A man, a plan is similar to Backrefs, but you have to match the reverse of the first group. Again, I couldn't find the proper way, if there is one, but the solution is short and works as well.

^(\w)(\w)\w*?\2\1$

Two groups, one letter each, followed by 0 or more letters, followed by the second group and then the first group, eventually reversing the order.

I will get back to Prime in a later post perhaps.

Four is nice. There might be a possibility of nested groups here though, just to make it shorter.

(\w)\w\1\w\1\w\1

Stay tuned for part 2. If I am ever able to solve the rest.

No comments:

Post a Comment