Don’t Be Greedy

Regular expressions are greedy—not the Wall Street/Gordon Gekko kind of greed, but they are greedy all the same. The regular expression greed means that a regular expression wants to match as much of a string as it can. For example, given the string 'Www! Regular Expressions, I <3 u!', the excitementPattern (/Wo*w.*!/) will match the entire string instead of just the Www! part. This is because the .*! tells the regular expression to match everything (including the !) until it finds the last !. Sometimes greed is good, but if you want your regular expression not to be greedy, there is hope. Add a ? (wow, ? sure has a lot of super powers) after the * or +, and its greed will go away.

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.