构建用于发送评论的正则表达式

Building a Regex for Shipping Comments

Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895.

Shipped 1-95080 via other FedEx with tracking 729870539581, 729870539592.

这里有两个单独的 "comments" 或输入到单个订单评论数据中的数据。

我需要在评论数据中搜索 "carrier" 和单独的跟踪号,但它们的格式因承运人而异。

我们只使用 2 家承运商 USPS 和 FedEx 进行包裹追踪。我想创建一个函数来提取承运人类型并仅从这些评论中提取跟踪号,以将它们放入我们数据库中的各个位置以供将来使用。我只是讨厌正则表达式。

有没有人能给我指明正确的方向? (这也都在PHP)

如果格式始终相同,您可能会使用 strpos() and substr()

的组合

考虑到您的评论总是在字符串中包含 'USPS' 或 'FedEx',只需使用带有 strpos() 的条件。在这些情况下,您可能希望使用 strtoupper() 来确保大小写匹配:

if (strpos(strtoupper($yourCommentString), 'USPS') !== false)
    $carrier = 'USPS';
else
    $carrier = 'FedEx';

至于跟踪号码,我找到了一个不需要正则表达式的解决方案,假设这些号码始终跟在 'tracking ' 之后并以 ', ':

分隔
$string = 'Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895, 1Z2216FE0348543895';

$start = strpos($string, 'tracking ') + strlen('tracking ');
$trackString = substr($string, $start);

$allTrack = explode(', ', $trackString);

我听说你说讨厌正则表达式,但它可能对这种情况有用。 我写了一个可以帮助你的例子。

第一个短语:

<?php
$string = 'Shipped 1-95080 via other USPS with tracking 1Z2216FE0348543895.';
preg_match('/.+(?P<ship_num>\d{1}\-\d+).+via other (?P<company>\w+) with tracking (?<tracking_code>[\w,\s]+)/', $string, $match);

if(strpos($match['tracking_code'], ',')!==false) {
    $match['tracking_code'] = array_map(function($index) {
        return trim($index);
    }, explode(',', $match['tracking_code']));
}

echo $match['ship_num']; // this echo prints '1-95080'
echo $match['company']; // this echo prints 'USPS'
print_r($match['tracking_code']); // this print_r prints an array with the value '1Z2216FE0348543895'

?>

第二个:

<?php
$string = 'Shipped 1-95080 via other FedEx with tracking 729870539581, 729870539592.';
preg_match('/.+(?P<ship_num>\d{1}\-\d+).+via other (?P<company>\w+) with tracking (?<tracking_code>[\w,\s]+)/', $string, $match);

if(strpos($match['tracking_code'], ',')!==false) {
    $match['tracking_code'] = array_map(function($index) {
        return trim($index);
    }, explode(',', $match['tracking_code']));
}

echo $match['ship_num']; // this echo prints '1-95080'
echo $match['company']; // this echo prints 'FedEx'
print_r($match['tracking_code']); // this print_r prints an array with the values '729870539581' and '729870539592'

?>

此 RegExp 将捕获 3 个组:

(?P<ship_num>\d{1}\-\d+) 该组将捕获一个数字 (\d)、一个连字符 (\-) 和一些数字 (\d+).

(?P<company>\w+) 该组将只捕获一些字母字符(\w+)。

(?<tracking_code>[\w,\s]+) 最后,该组将捕获一些空格字符(\s)、逗号和字母字符(\w)。

在所有这些组中,我将每个组命名为(?P<group name>)。

工具 Regex101 可用于测试 RegExp。