Nikola
Nikola

Reputation: 15048

PHP regex look around with matching multiple occurrences

I have the text that looks like this:

const {
    b {
        description "Create B1"
        uri "ms:///a/v1/create-b"
    }
    c {
        description "Create C1"
        uri "ms:///a/v1/create-c"
    }
    d {
        description "Create D1"
        uri "ms:///a/v1/create-d"
    }
}

const {
    b {
        description "Create B2"
        uri "ms:///a/v1/create-b"
    }
    c {
        description "Create C2"
        uri "ms:///a/v1/create-c"
    }
    d {
        description "Create D2"
        uri "ms:///a/v1/create-d"
    }
}

I'm trying to get everything between const and this is what I came up with so far: const {(?s)(.*)}.*?(?=const). That gives me just the first occurrence, and I can't figure out how to get all the other ones (in the original file there are more const objects).

Any push in the right direction would be welcome 👍

The link where you can test this is here: https://regex101.com/r/I4W5cR/1

Upvotes: 3

Views: 40

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627126

You may leverage the fact that each match starts with const at the start of a line:

(?sm)^const {(.*?)}\s*\R(?=const|\Z)

See the regex demo

Details

  • (?sm) - s enables the DOTALL mode and m makes ^ match line start positions
  • ^ - line start
  • const { - a substring
  • (.*?) - Group 1: any zero or more chars, as few as possible
  • } - a } char
  • \s*\R - zero or more whitespaces and then a line break
  • (?=const|\Z) - immediately on the right, there must be const or end of string.

Upvotes: 1

Related Questions