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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

技术分享

以上是关于[Regular Expressions] Find a String that Precedes Another String ?= , ?!的主要内容,如果未能解决你的问题,请参考以下文章

ruby regular_expressions.rb

regular expressions

[Regular Expressions] Find Groups of Characters, and ?:

Python re module (regular expressions)

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

正则表达式小结(Regular Expressions)