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


How do I limit the number of characters in a wildcard match in a preg_match pattern?

在下面的代码片段中,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>"
?>  

在regex的开头添加.+,并获得组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

表达

函数

{n}

精确匹配n次,例如:点击测试"'w{2}"等于"'w'w";点击测试"a{5}"是否等于"aaaaa"

{m, n}

至少m次但不超过n次:点击测试"ba{1,3}"是否匹配"ba"、"咩"、"字样"

{m}

匹配至少n次:点击测试"'w'd{2,}"匹配"a12"、"_456"、"M12344"…

?

匹配1或0次,相当于{0,1}:点击测试"a[cd]?"匹配"、"交流"、"广告"。

  • 匹配1次或1次以上,相当于{1,}:点击测试"a+b"匹配"ab"、"艺术展"、"aaab"…

匹配0次或更多次,相当于{0,}:点击测试"'^*b"匹配"b"、"^ ^ ^ b"…

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

如果你说limit,你可以使用大括号例如:/'s{4}/这将选择所有连续4个空白字符