简体   繁体   中英

javascript regex match the string excluding ending pattern

Can anyone please help me with this:

I'm stuck with JS regular expression.

I have a string like:

idont test 33lkjrhguegh8438934hihfer TEST2 oidchschds

I want to match everything between test and TEST2 excluding TEST2 .

So the expected output would be:

test 33lkjrhguegh8438934hihfer

I've tried the following with no success :( :

(test)(.*)(?:(?!(TEST2)))
(test)(.*)(?:(TEST2))
(test)(.*)(?:(?!TEST2))
(test)(.*)(?:TEST2)
(test)(.*)(TEST2) //almost works but selects TEST2 also

You can use:

/(test.+?)TEST2/

and use captured group #1 or using a positive lookahead :

/test.+?(?=TEST2)/

RegEx Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM