RegEx(?) - 如何解析文本中的邮政编码?

时间:2021-02-01 00:29:06

I have a file that contains a mish-mash of cities, states, and zip codes. Example:

我有一个文件,其中包含各种城市,州和邮政编码。例:

Munson 11010 Shelter Island Heights. . . .. 11965 Brentwood 11717 Halesite 11743

Munson 11010 Shelter Island Heights。 。 。 .. 11965 Brentwood 11717 Halesite 11743

I need to grab all of the zip codes out of that text. They are only 5 digit (no 5+4), and there are no other numbers besides the zips. It seems like a pretty straightforward regex thing, but I have no idea at all how to make the expression.

我需要抓取该文本中的所有邮政编码。它们只有5位数(没有5 + 4),除拉链外没有其他数字。这似乎是一个非常简单的正则表达式,但我根本不知道如何制作表达式。

I know some PHP so that's my preferred language, if possible. Ideally I'd like it to display the output 1-zip-per-line so that I can copy/paste into something like Excel.

我知道一些PHP,如果可能的话,这是我的首选语言。理想情况下,我希望它显示输出1-zip-per-line,以便我可以复制/粘贴到Excel之类的东西。

Thanks for any help!

谢谢你的帮助!

3 个解决方案

#1


The following code should send you in the right direction:

以下代码应该向您发送正确的方向:

<?php
$str = 'Munson 11010 Shelter Island Heights. . . .. 11965 Brentwood 11717 Halesite 11743 ';

preg_match_all("/\d{5}/", $str, $matches);

print_r($matches);
?>

#2


preg_match_all('[^0-9]([0-9]{5})[^0-9]', $input, $out);
foreach($out as $val)
    echo $val[1] . "\n";

#3


Great! Thanks so much -- here's what I ended up using:

大!非常感谢 - 这就是我最终使用的内容:

preg_match_all("/\d{5}/", $input, $matches);

foreach($matches[0] as $zip){
    echo $zip.'<br/>';
    };

#1


The following code should send you in the right direction:

以下代码应该向您发送正确的方向:

<?php
$str = 'Munson 11010 Shelter Island Heights. . . .. 11965 Brentwood 11717 Halesite 11743 ';

preg_match_all("/\d{5}/", $str, $matches);

print_r($matches);
?>

#2


preg_match_all('[^0-9]([0-9]{5})[^0-9]', $input, $out);
foreach($out as $val)
    echo $val[1] . "\n";

#3


Great! Thanks so much -- here's what I ended up using:

大!非常感谢 - 这就是我最终使用的内容:

preg_match_all("/\d{5}/", $input, $matches);

foreach($matches[0] as $zip){
    echo $zip.'<br/>';
    };