【问题标题】:preg_replace, negate regex patternpreg_replace,否定正则表达式模式
【发布时间】:2017-03-09 21:09:09
【问题描述】:

这是我想要否定的模式:

[\+\-][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。

谢谢!

【问题讨论】:

    标签: regex preg-replace negate


    【解决方案1】:

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

    (?=.*[+-]\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;
    

    【讨论】:

    • 为什么投反对票?想知道增强答案的原因
    【解决方案2】:

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

    【讨论】:

    • 这应该是一条评论。
    • preg_match 将无法完成这项工作,因为要提取多个值。
    • 有用的版本,谢谢,但出于某种原因我必须使用 preg_replace。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 2016-07-11
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多