Search code examples
regexpreg-replacenegate

preg_replace, negate regex pattern


This is my pattern which i want to negate:

[\+\-][0-9\.]+

These are sample rows:

Stephane Robert (+1.5 Sets)
Stephane Robert (-1.5 Sets)
Philipp Kohlschreiber
Philipp Kohlschreiber (-1.5 Sets)
Philipp Kohlschreiber (+1.5 Sets)
Player Names (n)
Another Player-Player

I want to strip all but the numbers, matching the pattern, i.e. i want only the positive or negative float number.

+1.5
-1.5
-1.5
+1.5

I'm using php and preg_replace.

Thanks!


Solution

  • You can use this. This will also remove other lines which doesn't have the desired value.

    (?=.*[+-]\d+\.\d+).*([+-]\d+\.\d+).*|(.*)
    

    Explanation

    PHP Code sample

    $re = '/(?=.*[+-]\d+\.\d+).*([+-]\d+\.\d+).*|(.*)/m';
        $str = 'Stephane Robert (+1.5 Sets)
        Stephane Robert (-1.5 Sets)
        Philipp Kohlschreiber
        Philipp Kohlschreiber (-1.5 Sets)
        Philipp Kohlschreiber (+1.5 Sets)
        Player Names (n)
        Another Player-Player';
        $subst = '\\1';
    
        $result = preg_replace($re, $subst, $str);
    
        echo $result;