preg_replace,否定正则表达式模式

时间:2016-10-27 08:55:18

标签: regex preg-replace negate

这是我想要否定的模式:

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

这些是示例行:

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

我想剥除除了数字之外的所有数字,匹配模式,即我只想要正数或负数浮点数。

+1.5
-1.5
-1.5
+1.5

我使用的是php和preg_replace。

谢谢!

2 个答案:

答案 0 :(得分:1)

如果您想查找与您的模式匹配的字符串,只需使用preg_match()代替preg_replace()

答案 1 :(得分:0)

你可以用它。这也将删除其他没有所需值的行。

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

Explanation

  

PHP代码示例

$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;
相关问题