[Regular Expressions] Find a String that Precedes Another String ?= , ?!

Let's image tow cases for the following string:

var str = `foo
foobar
foobaz
fooboo`

First of all: we know how to capture foobar or fooboo:

var regex = /foo(bar|boo)/g

1: We want to capture any 'foo' which followed by 'bar' or 'boo', but we do NOT want 'bar' or 'boo' appear in our result:

So we can use:

?= 

so:

var regex = /foo(?=bar|boo)/g

2. We want to capture any 'foo' without 'bar' or 'boo' followed:

so we can use:

?!

so:

var regex = /foo(?!bar|boo)/g

原文地址:https://www.cnblogs.com/Answer1215/p/5189838.html