Jim
Jim

Reputation: 19

Regex match strings not in certain brackets

does anyone know how to code a regex to get all the 123s that are NOT in the apple and banana brackets in the following text?

apple = {
      123 1647 4939 5025 
}
grape = {
      1647 123 1647 4939 5025 
}
grape_number = 123
123 = {
      orang_number = 456
}
banana = {
       1647 123 1647 4939 5025 
}

Upvotes: 0

Views: 51

Answers (1)

logi-kal
logi-kal

Reputation: 7880

If your regex flavour allows non-fixed-width negative lookbehinds, you can use this regex:

(?<!(?:apple|banana) *= *{[^{}]*)123

See a demo here.


Otherwise, you can use some heuristics like for the expression below (working in PCRE):

(?<!apple)(?<!banana)(?<=\w) *= *{[^{}]*\K123|123(?![^{}]*\})

This matches every 123 that is not wrapped within curly brackets or, if it is, the brackets are not "assigned" to apple or to banana.

See a demo here.


If neither the \K operator is allowed, you can use this:

(?<!apple)(?<!banana)(?<=\w) *= *{[^{}]*(123)|(123)(?![^{}]*\})

and extract groups $1 and $2.

Upvotes: 1

Related Questions