PHP regex look around with matching multiple occurrences

Viewed 37

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

1 Answers

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.
Related