简体   繁体   中英

Regex to catch all cases

I have the following stringified javascript-snippet that I would like to capture each case using regex

// case 1
let something = 1
something++

// case 2
const somethingElse = 2
const x = somethingElse + 10 // whatever

// case 3
enter code here

Cases keep going infinitely.. so I am looking for a regex that captures each case with all belonging code up until the next case is reached.

example of the first match should be

// case 1
let something = 1
something++

The best I could get is the following, but it always disregard the last case

([\/]{2}[\s]*?case[\s\S]+?(?=[\/]{2}))

Obviously, the Lookahead is the reason, I had other forms of regex but couldn't get a bulletproof regex..

Note: all cases should be identified consistently. The example above is using a simple pattern case [digit]

Any help is appreciated!

You can use a simple alternation in your look ahead:

([\/]{2}[\s]*?case[\s\S]+?(?=[\/]{2}|$))

I just added |$ in the look ahead, which means: OR end of text

So it will look ahead for / or end of text.

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