Home > Enterprise >  Group(s) around a word
Group(s) around a word

Time:03-05

I request your help. I've been trying to get a specific regex to work but I can't get it to do what I need.

The regex will group anything around [test], not itself. For example,

Input: [{1,/;k1`\n\t[test]|}[{3\n\t,/[test;k1`\n\t[test][test]|}[{9\n\t,/;s2`\t\n{...}
Output: 
        Group 1: [{1,/;k1`\n\t
        Group 2: |}[{3\n\t,/[test;k1`\n\t
        Group 3: 
        Group 4: |}[{9\n\t,/;s2`\t\n
        Group n: {...}

Also works without it

Input: [{1,/;k1[tes]`\n\t
Output: 
       Group 1: [{1,/;k1[tes]`\n\t

*Note: regex uses Expression Flags: /ig

CodePudding user response:

If it's the PCRE regex engine then you can use \K to ignore the [test]

Then it just needs a lookahead for whatever else comes before [test] or the end of the string.

\[test\]\K|([\s\S]*?)(?=\[test\]|$)

In javascript you could capture what's not [test]

let re = /(?:\[test\]|^)([\s\S]*?)(?=\[test\]|$)/ig;
let match;
while ((match = re.exec(Input)) !== null) {
  console.log(match[1] '\n')
}

But to be fair, simply splitting the string on [test] seems also an option.

  • Related