简体   繁体   中英

How can I write this regex without using a look behind that isn't supported

I rarely use Regex's and I've gotten it to work on regex101.com

But I tried to use it and it says it's not supported by JS this is what I have

/(?<=[\\]|>])(.*?)(?=$|\\n)/g

https://regex101.com/r/sxUoDr/1

How can I substitute the look behind so it will work fine?

This is the data I'm trying to parse:

<100>11m
[RIP]25s
[RIP] 2m
[RIP] 7m
[RIP] 1m
[RIP]12s

I'm trying to extract the times away

In javascript there is no look behind but if you want to 'extract' all the data you can use RegExp#exec :

 const data = `<100>11m [RIP]25s [RIP] 2m [RIP] 7m [RIP] 1m [RIP]12s` const getData = data => { const regex = /[ >\\]]\\s*(.*)/g const found = [] let temp while(temp = regex.exec(data)){ if (temp[1]) found.push(temp[1]) } return found } console.log(getData(data)) 

And if you want to replace it you just have to add that extra selected char back:

 const data = `<100>11m [RIP]25s [RIP] 2m [RIP] 7m [RIP] 1m [RIP]12s`.replace(/([ >\\]])\\s*(.*)/g, '$1 found [$2]') console.log(data) 

Without using a look behind lets use .*\\W(\\w+)(?:\\n|$) to get your results. Regex Demo: https://regex101.com/r/zbvmfp/1

JavaScript Demo

 var pattern = /.*\\W(\\w+)(?:\\n|$)/g; var str = `<100>11m [RIP]25s [RIP] 2m [RIP] 7m [RIP] 1m [RIP]12s`; var result; while (result = pattern.exec(str)) { console.log(result[1]); } 

I don't think it can be written more simply than this...

 var rgx = /\\d+[ms]/g; // capture 1 or more digits followed by m or s var str = `<100>11m [RIP]25s [RIP] 2m [RIP] 7m [RIP] 1m [RIP]12s`; var res; while(res=rgx.exec(str)){ console.log(res[0]); } 

Javascript does not support lookup behind. You can use positive lookups.

Regex: /(?=\\d+(m|s)).*$/gm

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