如何在preg_match模式中限制通配符匹配中的字符数?

时间:2016-09-03 14:20:12

标签: php regex preg-match

在以下代码段中,pre_match返回第一个纬度读数,然后是经常阅读的经常读数。 我所追求的是最终的纬度/经度对 如何将两个读数之间的间距限制为最多4个字符? .*?表达式允许使用太多字符 我怎么能改变它以允许更小的数字?

<?php
$lcline="tuesday, 20th. light airs and clear weather. p.m. started at latitude 24 degrees 12 minutes took several azimuth, which gave the variation 16 degrees 30 minutes west. put the ship's company to three watches. wind variable; course south 21 degrees 30 minutes west; distance 28 miles; latitude 31 degrees 17 minutes, longitude 17 degrees 19 minutes west; at noon, funchall, island of madeira, north 13 degrees east, 76 miles. ";

preg_match('/(latitude\s+\d+\s+degrees\s+\d+\s+minutes.*?longitude\s+\d+\s+degrees\s+\d+\s+minutes)/', $lcline, $results);
echo "results=".$results[0]."<BR><BR>"
?>  

3 个答案:

答案 0 :(得分:1)

在正则表达式的开头添加.+并从第1组获得结果:

preg_match('/.+(latitude\s+\d+\s+degrees\s+\d+\s+minutes.*?longitude\s+\d+\s+degrees\s+\d+\s+minutes)/s', $lcline, $results);
echo "results=",$results[1],"\n";

<强>输出:

results=latitude 31 degrees 17 minutes, longitude 17 degrees 19 minutes

答案 1 :(得分:0)

  

表达

     

功能

     

{n}

     

完全匹配n次,例如:点击测试“\ w {2}”等于“\ w \ w”;   点击测试“a {5}”等于“aaaaa”

     

{m,n}

     

至少m但不超过n次:点击测试“ba {1,3}”匹配   “BA”, “BAA”, “BAAA”

     

{m,}

     

匹配至少n次:点击测试“\ w \ d {2,}”匹配   “A12”, “_ 456”, “M12344” ...

     

     

匹配1或0次,相当于{0,1}:点击测试“a [cd]?”   匹配“a”,“ac”,“ad”。

     
      
  • 匹配1次或更多次,相当于{1,}:点击测试“a + b”匹配   “AB”, “AAB”, “AAAB” ...

  •   
  •   
     

匹配0次或更多次,相当于{0,}:点击测试“\ ^ * b”   匹配“b”,“^^^ b”......

参考:http://www.regexlab.com/en/regref.htm

答案 2 :(得分:0)

如果你说限制,你可以使用花括号 例如:/\s{4}/这将连续选择4个空格字符