Sylvain Elias
Sylvain Elias

Reputation: 21

How to not match character in capturing group

I have a capturing grp numbered 2 that catches a number but i need the regex to match everything except what's in \2 I tried [^\2] but it's still matching it

Regex:

##[^\n]*\n## \(CR (\d)\) RM (\d): [^\n]*\n##[^\n]*\n\(CR \1\) SM \2: [^\n]*\n(##[^\n]*\n\(CL **[^\2]**\) RM \2: [^\n]*\n)+

Text:

(Chat room 1) Received message from client 4: Nice to meet you!

(CR 1) RM 4: Nice to meet you!

(Chat room 1) Sent message to all connected clients except client 4: Nice to meet you!

(CR 1) SM 4: Nice to meet you!

(Client 1) Received message from client 4: Nice to meet you!

(CL 3) RM 4: Nice to meet you!

(Client 1) Received message from client 4: Nice to meet you!

(CL 4) RM 4: Nice to meet you!

I want the last two lines not to be matched

Demo

Upvotes: 1

Views: 115

Answers (2)

The fourth bird
The fourth bird

Reputation: 163287

You could make use of a negative lookahead and then match a digit (?!\2)\d to not match the last line

##[^\n]*\n## \(CR (\d)\) RM (\d): [^\n]*\n##[^\n]*\n\(CR \1\) SM \2: [^\n]*\n(##[^\n]*\n\(CL (?!\2)\d\) RM \2: [^\n]*\n)+

Regex demo

As the last group is a repeated capturing group, you could also make it non capturing (?: if you don`t need the group itself.

Repeating a captured group will only capture the value of the last iteration.

(?:##[^\n]*\n\(CL (?!\2)\d\) RM \2: [^\n]*\n)+
^^^

Regex demo

Upvotes: 1

Emma
Emma

Reputation: 27723

I guess maybe an expression similar to,

##[^\n]*\n## \(CR (\d)\) RM (\d): [^\n]*\n##[^\n]*\n\(CR \1\) SM \2: [^\n]*\n((?!##[^\n]*\n\(CL \2\) RM \2: [^\n]*\n)##[^\n]*\n\(CL .*?\) RM \2: [^\n]*\n)+

might be OK to look into, but I'm not so sure if it would be close to what you have in mind.

Demo

Upvotes: 0

Related Questions