PHP preg_match:逗号分隔的小数

时间:2013-06-14 18:37:29

标签: php regex

此正则表达式找到正确的字符串,但只返回第一个结果。如何让它搜索文本的其余部分?

$text =",415.2109,520.33970,495.274100,482.3238,741.5634
655.3444,488.29980,741.5634";

preg_match("/[^,]+[\d+][.?][\d+]*/",$text,$data);

echo $data;

跟进: 我正在推动这个脚本的最初期望,而我正处于我正在提取更多冗长数据的地步。用这个浪费了很多时间......任何人都可以轻松一点吗? 继承我的字符串:

155.101.153.123:simple:mass_mid:[479.0807,99.011, 100.876],mass_tol:[30],mass_mode:  [1],adducts:[M+CH3OH+H],
130.216.138.250:simple:mass_mid:[290.13465,222.34566],mass_tol:[30],mass_mode:[1],adducts:[M+Na],

并且继承我的正则表达式: “/ mass_mid:[((?:\ d +)(?:。)(?:\ d +)(?:)*)/”

我真的很想听到这个!有人可以告诉我如何从结果中排除行 mass_mid:[,并保留逗号分隔值吗?

3 个答案:

答案 0 :(得分:2)

使用preg_match_all而不是preg_match

从PHP手册:

(`preg_match_all`) searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

After the first match is found, the subsequent searches are continued on from end of the last match.

http://php.net/manual/en/function.preg-match-all.php

答案 1 :(得分:2)

不要使用正则表达式。使用split将您的输入拆分为逗号。

正则表达不是一个魔杖,你会在每个涉及字符串的问题上挥手。

答案 2 :(得分:0)

描述

要提取可能包含一个小数点的数值列表,那么您可以使用此正则表达式

\d*\.?\d+

enter image description here

PHP代码示例:

<?php
$sourcestring=",415.2109,520.33970,495.274100,482.3238,741.5634
655.3444,488.29980,741.5634";
preg_match_all('/\d*\.?\d+/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

产生匹配

$matches Array:
(
    [0] => Array
        (
            [0] => 415.2109
            [1] => 520.33970
            [2] => 495.274100
            [3] => 482.3238
            [4] => 741.5634
            [5] => 655.3444
            [6] => 488.29980
            [7] => 741.5634
        )

)
相关问题