Matthew Davis
Matthew Davis

Reputation: 398

Regex to match docblock for specific function

I'm trying to write a regex to match a docblock / phpdoc comment for a specific function.

For example, given the following class:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

I want to write a regex that can match the docblock for a specific method, identified by its name.

I've tried using a positive lookahead to match the function definition, but trying to match the boot method's docblock always selects from the register method's docblock:

(\h*/\*\*(.|\n)*\*/\n)(?=\h*.* boot)

Gives me:

Regex is broken :sadface:

I do want to capture the preceding whitespace before the opening of the comment, and the final newline before the line with the function definition.

Any help would be gratefully received!

Upvotes: 1

Views: 299

Answers (1)

The fourth bird
The fourth bird

Reputation: 163457

For the given example, you might use

^\h*/\*\*(?:\R\h*\*.*)*\R\h*\*/\R(?=.*\bfunction boot\b)
  • ^ Start of string
  • \h*/\*\* Match optional spaces and /**
  • (?:\R\h*\*.*)* Match all following lines that start with optional spaces and *
  • \R\h*\*/ Match a newline, optional spaces and */
  • \R Match the last newline before the line with the function definition
  • (?=.*\bfunction boot\b) Positive lookahead to assert function boot to the right

Regex demo

Upvotes: 2

Related Questions