I Love Regex

I Love Regex

regex is awesome. Its powerful, its fun, and it can make you extremely efficient. There are 2 places where regex is most needed:

  1. Fixing code
  2. Validating input

Understanding Negative Lookahead

Let me walk you through an example of how to use negative lookahead:

  1. We start with “hello”. Pretty simple.

  2. Then we first use a negated lookahead: (?!world). Which basically says “match one time the string ‘world’ NOT followed by anything” (which is the .). So again, we’re matching 1 time, the word “world” that is NOT followed by anything.

  3. Then, we need to not just match 1 time. That would just give us 1 character. We need to match everything until we get there. Just like the “match until character” had the +, we need a + here as well.

  4. But you can’t just add a +. And you can’t wrap the whole thing in square brackets like a normal regex. So we need to wrap in parentheses so we can use the +: ((?!word).)+

  5. BUT, we have a problem that we just used parentheses, which are going to capture the result. So we now need to NON CAPTURE those parentheses so they stay out of the way: (?:(?!world).)+