Reputation: 398
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:
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
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 rightUpvotes: 2