Search code examples
phpregexlaravel

Regex pattern to capture ClassName not working if Namespace and ClassMethod are made optional


Regexr Link

(?<Namespace>[^@]*)?[\\\/](?<ClassName>[\w\d]*)@?(?<ClassMethod>[^@]*)?

I'm trying to Capture Namespace, ClassName and ClassMethod from a string in which Namespace and ClassMethod are optional.

This pattern handles capturing the three well if all three are present. But fails if ClassName is the only thing present.

The only solution I found was to make the last slash optional

(?<Namespace>[^@]*)?[\\\/]?(?<ClassName>[\w\d]*)@?(?<ClassMethod>[^@]*)?

But this does not catch the ClassName at all and captures it in Namespace instead.

What am I doing wrong?

String: Api\Blah\Blah\CarController@doStuff

Pattern: (?<Namespace>[^@]*)?[\\\/]?(?<ClassName>[\w\d]*)@?(?<ClassMethod>[^@]*)?

Expecting: Namespace: Api\Blah\Blah ClassName: CarController ClassMethod: doStuff


Solution

  • I solved it by using a non-capturing group.

    (?:(?<Namespace>[\w\d\\\/]*)[\\\/])?(?<ClassName>[\w\d]*)@?(?<ClassMethod>[^@]*)?
    

    Regexr link has been updated with the pattern that worked for me.