skip to Main Content

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

2

Answers


  1. Because the number of spaces are not known, one way to do it is to negate the since:

    ^(?im)s**s*(?!@since)[a-z]+s*:s*1.0.0
    

    and then using a capture group, 1.0.0 can be matched:

    ^(?im)s**s*(?!@since)[a-z]+s*:s*(1.0.0)
    
    • ^: means start of the line.
    • (?im): means insensitive and multiline flags.
    • s*: means zero or more spaces.
    • *: literal *
    • (?!@since): excludes the since.
    • [a-z]+: one or more a to z chars (other chars can be added as well)
    • (1.0.0): is a capture group including 1.0.0 and can be addressed as $1

    For using in VS Code environment, the inline flag should be removed:

    (?!@since)[ws]+:s*(1.0.0)|^s*w+s*(s*['"]s*[^'"]*['"]s*,s*['"]s*([^'"]*)['"]s*)s*;
    

    It seems that you’re trying to do a find-replace operation. In that case:

    • simply match * @since 1.0.0 using a simple regex (@sinces+(1.0.0)) and replace it with a unique string such as A0P8x&2%.
    • Then, simply search for 1.0.0 and make your changes.
    • Finally, replace A0P8x&2% with * @since 1.0.0.
    Login or Signup to reply.
  2. You can use an additional positve lookbehind to only look back after a non-whitespace:

    (?<=S)(?<!since)s*1.0.0
    

    See this demo at regex101

    This will prevent the negative lookbehind to succeed if preceded by a whitespace.
    Be aware that this will require at least one character (non-whitespace) before 1.0.0

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search