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:
- Fixing code
- Validating input
Understanding Negative Lookahead
Let me walk you through an example of how to use negative lookahead:
We start with “hello”. Pretty simple.
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.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.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).)+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).)+