我正在尝试使用正则表达式来提取某种语法,在我的例子中是“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);
但仍然没有运气。请提供任何建议,因为我没有很强的正则表达式知识。谢谢。
最佳答案
你可以使用
\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
)
关于PHP正则表达式提取特殊字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43779994/