我想捕获组1中的所有者或生成器,否则在组2中遇到直到连字符和/或空格后跟数字的所有文本,然后从以下文本直到组3中行尾的任何数字: -
PRD Hervey Bay 07 2525 1919
RG Sprake & Co Maryborough 4141 2424
Owner Robert - 0429 966 391
Owner Maureen - 07 8888 4444 - 0422000 111
Owner Wayne - 0430 555 666
Builder Scott - 0444 555 777
我当前正在使用的表达式:-
/(Owner|Builder)([^-]+)-|\s+(\d.*)/gm
第2组中的“ PRD Hervey Bay”和“ RG Sprake&Co Maryborough”不匹配。
任何帮助表示赞赏!
特伦特。
答案 0 :(得分:1)
您可以使用此正则表达式获取所需的结果:
/^(Owner |Builder )?(.*?)(?=-| \d)[- ]+(.*)$/m
它查找(可选)字符串Owner
或Builder
;后跟一些最少的字符,直到-
或空格后跟一个数字;后跟一定数量的-
或空格,然后是字符,直到行尾。要在PHP中使用:
$text = <<<EOD
PRD Hervey Bay 07 2525 1919
RG Sprake & Co Maryborough 4141 2424
Owner Robert - 0429 966 391
Owner Maureen - 07 8888 4444 - 0422000 111
Owner Wayne - 0430 555 666
Builder Scott - 0444 555 777
EOD;
preg_match_all('/^(Owner |Builder )?(.*?)(?=-| \d)[- ]+(.*)$/m', $text, $matches);
print_r($matches);
输出:
Array (
[0] => Array (
[0] => PRD Hervey Bay 07 2525 1919
[1] => RG Sprake & Co Maryborough 4141 2424
[2] => Owner Robert - 0429 966 391
[3] => Owner Maureen - 07 8888 4444 - 0422000 111
[4] => Owner Wayne - 0430 555 666
[5] => Builder Scott - 0444 555 777
)
[1] => Array (
[0] =>
[1] =>
[2] => Owner
[3] => Owner
[4] => Owner
[5] => Builder
)
[2] => Array (
[0] => PRD Hervey Bay
[1] => RG Sprake & Co Maryborough
[2] => Robert
[3] => Maureen
[4] => Wayne
[5] => Scott
)
[3] => Array (
[0] => 07 2525 1919
[1] => 4141 2424
[2] => 0429 966 391
[3] => 07 8888 4444 - 0422000 111
[4] => 0430 555 666
[5] => 0444 555 777
)
)
请注意,这确实在最后一组中保留了一些空格和-
,您可以使用array_walk
轻松删除它们(如果需要):
array_walk($matches[3], function (&$v) { $v = preg_replace('/[^\d]/', '', $v); });