phpregexnegative-lookbehind

Negative lookbehind doesn't seem to work as expected


Suppose the PHP code

/**
 * @since             1.0.0 <--- this shouldn't be matched
 * @package           blah blah blah
 * Version:           1.0.0 <--- this should be matched
 */

/**
 * Fired during plugin activation.
 *
 * This class defines all code necessary to run during the plugin's activation.
 *
 * @since      1.0.0 <--- this shouldn't be matched
 * @package    blah blah
 * @subpackage blah blah
 * @author     blah blah
 */

define( 'PLUGIN_VERSION', '1.0.0' ); // <--- this should be matched

I want to match the 1.0.0 occurrences that are not after the @since string, so I only want to match the second and third ones.

This regex has to work in VS.Code and I searched for this pattern (?<!since)(?:\s*)1\.0\.0 which doesn't seem to work. What am I missing?

https://regex101.com/r/BGtDx6/1


Solution

  • You can add another lookbehind to only look back where no whitespace is before:

    (?<!\s)(?<!since)\s*1\.0\.0
    

    See this demo at regex101

    This will prevent the latter lookbehind to succeed where preceded by a whitespace.
    If needed you can capture whitespace and reinsert in the replacement string like this.