2016-10-27 39 views
1

這是我的方式,我想否定:了preg_replace,否定正則表達式

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

謝謝!

回答

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; 
+0

爲什麼downvoted?想知道提高答案的理由 –

1

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

+3

這應該是一個評論。 – Toto

+1

而'preg_match'不會完成這項工作,因爲有多個要提取的值。 –

+0

有用的版本,謝謝,但我不得不使用preg_replace出於某種原因。 – NTsvetkov