Questions & Answers

Python regex for selecting multiple lines of code

I'd like to create a python Regex that can select a Terraform resource block in its entirety. There are multiple resource blocks in a file (example below), and I want to select each one separately.

I've tried the following regexes. The first one gets caught up when there are multiple closing brackets in the code. The second one just selects the whole file.

1) match ='resource.*?\{(.*?)\}', code, re.DOTALL)
2) match ='resource.*?\{(.*)\}', code, re.DOTALL)

Sample file:

resource "aws_s3_bucket_notification" "aws-lambda-trigger" {
  bucket =
  lambda_function {
    lambda_function_arn = aws_lambda_function.test_lambda.arn
    events              = ["s3:ObjectCreated:*"]
    filter_prefix       =  var.prefix
    filter_suffix       =  var.suffix
resource "aws_s3_bucket" "newbucket" {
    bucket = var.bucket_name
    force_destroy = true
    acl = var.acl_value
2023-01-24 00:30:04
Does this answer your question? Python: How to match nested parentheses with regex?
Answers(0) :