To say that using regular expressions is like hitting your face on the keyboard until something matches is not an entirely untrue statement, if you were to look at some examples:
matching an IP address:\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b
finding email addresses:
\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b
finding an 'Al' next to the largest number in a text:\bAL\w*( \w\.)? S\w+ \d{2,},\d+
I think the picture here is becoming clearer: Regular Expressions, or RegExps, are valuable, albeit indecipherable, strings of code that work to find or find-and-replace certain strings inside of other strings. They're useful when dealing with large strings, but also in a lot of other places. They're the tool of the power-user who parses text with minimal code and maximum results.
The term 'regular expression' was coined by Warren McCulloch and Walter Pitts, a neuroscientist and logician respectively, who in 1943 published a paper in Mathematical Biophysics which attempted to understand 'how the human brain could produce complex patterns using simple cells that are bound together' (link). Among other ideas, the paper laid out the term Regular Expression, which by some amazing jump between disciplines came to influence computer scientists (as did various other ideas from other disciplines). In 1968, Ken Thompson descriped a RegExp compiler—the idea was to allow users to match patterns in text files. This functionality was then implemented in the text editor 'ed'. To do a RegExp search in ed, you had to write g/<regular expression>/p
: essentially, g/re/p
. g
meant 'global search' and p
meant 'print', This command eventually resulted in a form we use even in Ruby: grep
; we got it via Unix, and then Perl, but other languages like Java also implemented RegExps.
More honestly, RegExps are really a great and valuable tool. They tend to be difficult to remember, use, and understand, but also powerful and often speedy. I have dipped the barest toe into the waters of regular expressions, but I intend to learn to use them myself with Ruby and text parsing.
Resources:
- The Bastards Book of Regular Expressions
- RegexOne: an interactive tutorial
- Regex Crossword: regular expression challenges
- "Verbal Expressions in Ruby": a gem to make regexes easier to write
- envatotuts+: regular expression tutorials
- "You Don't Know Anything About Regular Expressions: a Complete Guide"
- "Regular Expressions: a brief history"
- "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby, ...)"
- Wikipedia: regular expression