PHP正则表达式提取特殊字符串

时间:2017-05-04 10:12:29

标签: php regex

我正在尝试使用正则表达式来提取某种语法,在我的情况下类似于“10.100”或“20.111”,其中2个数字用点(。)分隔。因此,如果我提供“a 10.100”,它将从字符串中提取10.100。如果我提供“a 10.100 20.101”,它将提取10.100和20.101。

到目前为止,我已尝试使用

preg_match('/^.*([0-9]{1,2})[^\.]([0-9]{1,4}).*$/', $message, $array);

但仍然没有运气。请提供任何建议,因为我没有强大的正则表达式知识。感谢。

2 个答案:

答案 0 :(得分:3)

您可以使用

\b[0-9]{1,2}\.[0-9]{1,4}\b

请参阅regex demo

<强>详情:

  • \b - 领先的单词边界
  • [0-9]{1,2} - 1或2位数字
  • \. - 一个点
  • [0-9]{1,4} - 1到4位
  • \b - 一个尾随字边界。

如果您不关心整个单词选项,只需删除\b即可。另外,要匹配一个或多个数字,您可以使用+代替限制量词。所以,也许

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

也适合你。

查看PHP demo

$re = '/[0-9]+\.[0-9]+/';
$str = 'I am trying to use regex to extract a certain syntax, in my case something like "10.100" or "20.111", in which 2 numbers are separated by dot(.) . So if I provide "a 10.100", it will extract 10.100 from the string. If I provide "a 10.100 20.101", it will extract 10.100 and 20.101.';
preg_match_all($re, $str, $matches);
print_r($matches[0]);

输出:

Array
(
    [0] => 10.100
    [1] => 20.111
    [2] => 10.100
    [3] => 10.100
    [4] => 10.100
    [5] => 20.101
    [6] => 10.100
    [7] => 20.101
)

答案 1 :(得分:2)

正则表达式: /\d+(?:\.\d+)/

  

1。 \d+,用于匹配一个或多个数字。

     

2。 (?:\.\d+)用于匹配数字,后跟.,如.1234

Try this code snippet here

<?php

ini_set('display_errors', 1);
$string='a 10.100 20.101';
preg_match_all('/\d+(?:\.\d+)/', $string, $array);
print_r($array);

<强>输出:

Array
(
    [0] => Array
        (
            [0] => 10.100
            [1] => 20.101
        )

)