UFO ET IT

추적 번호에 대한 정규식 패턴

ufoet 2020. 12. 31. 22:43
반응형

추적 번호에 대한 정규식 패턴


어느 회사 추적 번호가 패키지에 대해 지정된 추적 번호인지 확인하기위한 좋은 장소 또는 패턴을 아는 사람이 있습니까? 아이디어는 바코드를 스캔 한 후 패턴이있는 배송 추적 번호를 확인하고 배송 된 회사를 보여줍니다.


jquery를 통해 일치시키고 자동으로 적절한 운송 업체를 선택하기 위해 작업 중이므로 이에 대한 업데이트를 게시 할 것이라고 생각했습니다. 내 프로젝트와 일치하는 정규식 목록을 작성했으며 UPS FedEX 및 USPS에서 많은 추적 번호를 테스트했습니다.

일치하지 않는 것을 발견하면 여기에서 의견을 통해 알려 주시면 이에 대해서도 생각해 드리겠습니다.

UPS :

/\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b/

FedEX : (3 개의 다른 것)

/(\b96\d{20}\b)|(\b\d{15}\b)|(\b\d{12}\b)/
/\b((98\d\d\d\d\d?\d\d\d\d|98\d\d) ?\d\d\d\d ?\d\d\d\d( ?\d\d\d)?)\b/
/^[0-9]{15}$/

USPS : (4 개의 다른 것)

/(\b\d{30}\b)|(\b91\d+\b)|(\b\d{20}\b)/
/^E\D{1}\d{9}\D{2}$|^9\d{15,21}$/
/^91[0-9]+$/
/^[A-Za-z]{2}[0-9]+US$/

나는 이것들을 스스로 생각해 내지 않았다는 점에 유의하십시오. 나는 단순히 여기에 언급 된 일부를 포함하여 여러 소스에서 목록을 검색하고 컴파일했습니다.

감사

편집 : 누락 된 끝 구분 기호를 수정했습니다.


Recorded Delivery & Special Delivery 추적 참조에 대한 정규식을 위해 Royal Mail을 눌렀지만 그리 멀지 않았습니다. 내가 직접 굴릴 수있는 완전한 규칙조차도 그 이상이었다.

기본적으로 약 1 주일 정도 걸리고 서비스 유형을 나타내는 다양한 조합의 문자를 가지고 돌아온 후에도 분명히 유효하지만 문서화되지 않은 추가 조합이 있음을 보여주는 경험을 통해 예제를 제공 할 수있었습니다.

참조는 Jefe의 /^[A-Za-z]{2}[0-9]+GB$/정규식이 설명 할 것으로 보이는 표준 국제 형식을 따릅니다 .

XX123456789GB

이것이 표준 형식 인 것처럼 보이지만, 즉 대부분의 국제 우편은 마지막 두 글자가 원산지를 나타내는 동일한 형식을 가지고 있습니다.이 '표준'에 대해 더 이상 알 수 없었습니다. (모든 설명 환영합니다!).

특히 Royal Mail은 서비스 수준을 표시하기 위해 처음 두 글자를 사용하는 것 같습니다. Special Delivery를 나타내는 접두사 목록을 작성했지만 100 % 완전하다고 확신하지는 않습니다.

AD AE AF AJ AK AR AZ BP CX DS EP HC HP KC KG
KH KI KJ KQ KU KV KW KY KZ PW SA SC SG SH SI
SJ SL SP SQ SU SW SY SZ TX WA WH XQ WZ

이러한 접두사 중 하나가 없으면 서비스는 배달 확인을 제공하지만 추적은 제공하지 않는 Recorded Delivery입니다.

일반적으로 S, X 또는 Z의 포함은 더 높은 서비스 수준을 나타내는 것으로 보이며 접두사에 이러한 문자가있는 일반 배달 배달 항목을 본 적이 없다고 생각합니다.

그러나 보시다시피 정규식을 사용하여 서비스 수준을 확인해야 할 경우 테스트해야 할 접두사가 많이 있으며 Royal Mail이 포괄적 인 규칙 집합을 제공 할 수 없다는 사실을 감안할 때 서비스 수준을 테스트하려고 할 수 있습니다. 효과 없는.


JUST USPS (미국 우편 서비스) 추적 번호를 확인해야합니다. WikiAnswers에 따르면 내 숫자 형식은 다음과 같습니다.

USPS는 보통 "E"로 시작하는 다른 문자, 9 자리 숫자 및 2 개의 추가 문자로 시작하는 특급 우편으로 만 추적을 제공합니다. USPS에는 16 자리에서 22 자리 사이의 다른 서비스에 대한 "라벨 번호"가 있습니다.

http://wiki.answers.com/Q/How_many_numbers_in_a_USPS_tracking_number

지난 2 년 동안 개인 배송에서받은 모든 라벨 번호는 9로 시작하므로 라벨 번호는 "9"로 시작합니다.

따라서 WikiAnswers가 정확하다고 가정하면 다음 두 가지 모두와 일치하는 정규식이 있습니다.

/^E\D{1}\d{9}\D{2}$|^9\d{15,21}$/

매우 간단합니다. 분석은 다음과 같습니다.

^E       - Begins w/ E  (For express number)
\D{1}    - followed by another letter
\d{9}    - followed by 9 numbers
\D{2}    - followed by 2 more letters
$        - End of string

|        - OR

^9       - Basic Track & Ship Number
\d{15,21}   - followed by 15 to 21 numbers
$        - End of string

www.gummydev.com의 정규식 테스터를 사용하면이 패턴이 두 테스트 문자열과 일치합니다.

익스프레스 메일 : EK225651436US

라벨 번호 : 9410803699300003725216

** 참고 : ColdFusion (I am)을 사용하는 경우 패턴에서 첫 번째와 마지막 "/"를 제거하십시오.


다음은 미국 주요 이동 통신사의 샘플 번호입니다.

USPS:
70160910000108310009   (certified)
23153630000057728970   (signature confirmation)
RE360192014US          (registered mail)      
EL595811950US          (priority express)
9374889692090270407075 (regular)

FEDEX:
810132562702  (all seem to follow same pattern regardless) 
795223646324
785037759224

UPS:
K2479825491         (UPS ground)
J4603636537         (UPS next day express)
1Z87585E4391018698  (regular)

내가 사용중인 패턴 (php 코드). 네, 포기하고 모든 패턴에 대한 테스트를 시작했습니다. 두 번째 UPS를 작성해야했습니다.

public function getCarrier($trackingNumber){



    $matchUPS1      = '/\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b/';
    $matchUPS2      = '/^[kKJj]{1}[0-9]{10}$/';

    $matchUSPS0     = '/(\b\d{30}\b)|(\b91\d+\b)|(\b\d{20}\b)/';
    $matchUSPS1     = '/(\b\d{30}\b)|(\b91\d+\b)|(\b\d{20}\b)|(\b\d{26}\b)| ^E\D{1}\d{9}\D{2}$|^9\d{15,21}$| ^91[0-9]+$| ^[A-Za-z]{2}[0-9]+US$/i';
    $matchUSPS2     = '/^E\D{1}\d{9}\D{2}$|^9\d{15,21}$/';
    $matchUSPS3     = '/^91[0-9]+$/';
    $matchUSPS4     = '/^[A-Za-z]{2}[0-9]+US$/';
    $matchUSPS5     = '/(\b\d{30}\b)|(\b91\d+\b)|(\b\d{20}\b)|(\b\d{26}\b)| ^E\D{1}\d{9}\D{2}$|^9\d{15,21}$| ^91[0-9]+$| ^[A-Za-z]{2}[0-9]+US$/i';

    $matchFedex1    = '/(\b96\d{20}\b)|(\b\d{15}\b)|(\b\d{12}\b)/';
    $matchFedex2    = '/\b((98\d\d\d\d\d?\d\d\d\d|98\d\d) ?\d\d\d\d ?\d\d\d\d( ?\d\d\d)?)\b/';
    $matchFedex3    = '/^[0-9]{15}$/';


    if(preg_match($matchUPS1, $trackingNumber) || 
        preg_match($matchUPS2, $trackingNumber))
     {
        echo('UPS');

        $carrier = 'UPS';
        return $carrier;
    } else if(preg_match($matchUSPS0, $trackingNumber) || 
              preg_match($matchUSPS1, $trackingNumber) ||
              preg_match($matchUSPS2, $trackingNumber) ||
              preg_match($matchUSPS3, $trackingNumber) ||
              preg_match($matchUSPS4, $trackingNumber) ||
              preg_match($matchUSPS5, $trackingNumber)) {

        $carrier = 'USPS';
        return $carrier;
    } else if (preg_match($matchFedex1, $trackingNumber) || 
               preg_match($matchFedex2, $trackingNumber) || 
               preg_match($matchFedex3, $trackingNumber)) {

        $carrier = 'FedEx';
        return $carrier;
    } else if (0){
        $carrier = 'DHL';
        return $carrier;
    } 



    return;

}

다음을 시도해 볼 수 있습니다 (보장되지 않음).

UPS :

\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b

UPS :

\b(1Z ?\d\d\d ?\d\w\w ?\d\d ?\d\d\d\d ?\d\d\d ?\d|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b

USPost :

\b(\d\d\d\d ?\d\d\d\d ?\d\d\d\d ?\d\d\d\d ?\d\d\d\d ?\d\d|\d\d\d\d ?\d\d\d\d ?\d\d\d\d ?\d\d\d\d ?\d\d\d\d)\b

그러나 사용하기 전에 테스트하십시오. RegexBuddy를 추천 합니다 .


다른 사람이이를 검색하는 데 도움이되는 경우 일반적인 형식을 해결하는 간단한 Python 클래스가 있습니다. Gist # 541851


잠시 동안 이것을 조사하고 대부분 여기에 대한 답변을 기반으로 만들었습니다.
이것들은 너무 관대하지 않고 모든 것을 포함해야합니다.
UPS :
/^(1Z\s?[0-9A-Z]{3}\s?[0-9A-Z]{3}\s?[0-9A-Z]{2}\s?[0-9A-Z]{4}\s?[0-9A-Z]{3}\s?[0-9A-Z]$|[\dT]\d{3}\s?\d{4}s?\d{3})$/i

USPS :
/^(EA|EC|CP|RA)\d{9}(\D{2})?$|^(7\d|03|23|91)\d{2}\s?\d{4}\s?\d{4}\s?\d{4}\s?\d{4}(\s\d{2})?$|^82\s?\d{3}\s?\d{3}\s?\d{2}$/i

페덱스 :
/^(((96|98)\d{5}\s?\d{4}$|^(96|98)\d{2})\s?\d{4}\s?\d{4}(\s?\d{3})?)$/i


내가 작성한 eBay 응용 프로그램에서 다음을 사용합니다.

USPS 국내 :

/^91[0-9]+$/

USPS International :

/^[A-Za-z]{2}[0-9]+US$/

FedEx :

/^[0-9]{15}$/

그러나 모든 USPS 국내 레이블이 "91"로 시작하므로 이것은 eBay / Paypal에 한정 될 수 있습니다. 모든 USPS International 레이블은 두 문자로 시작하고 "US"로 끝납니다. 내가 아는 한 FedEx는 15 개의 임의의 숫자 만 사용합니다.

(Please note that these regular expressions assume all spaces are removed. It would be fairly easy to allow for spaces though)


Check out this github project that lists a lot of PHP tracking regexes. https://github.com/darkain/php-tracking-urls


Here are the ones I am now using in my Java app. These are determined by my experience of sucking tracking numbers out of shipping confirmation emails from a whole pile of drop ship services. I just made a new USPS one from scratch since none of the ones I found worked for some of my numbers based on example numbers on the USPS site. These only work for US tracking codes because we only sell in the US.

private final Pattern UPS_TRACKING_NUMBER =
    Pattern.compile("[^A-Za-z0-9](1Z[A-Za-z0-9]{6,})",
        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

private final Pattern FEDEX_TRACKING_NUMBER =
    Pattern.compile("\\b((96|98)\\d{18,20}|\\d{15}|\\d{12})\\b",
        Pattern.MULTILINE);

private final Pattern USPS_TRACKING_NUMBER =
    Pattern.compile("\\b(9[2-4]\\d{20}(?:(?:EA|RA)\\d{9}US)?|(?:03|23|14|70)\\d{18})\\b",
        Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); 

I believe FedEx is 12 digits:

^[0-9]{12}$

I also came across tracking numbers from FedEx with 22 digits recently, so watch out! I haven't found any good reference for the FedEx's general format yet.

FedEx Example #: 9612019059803563050071


Here's an up to date regex for UPS (works with regular and Mail Innovation type tracking numbers):

\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d|\d\d\d ?\d\d\d ?\d\d\d|\d{22,34})\b


Late to the party however, the below will work with 26 char USPS numbers as well.

/(\b\d{30}\b)|(\b91\d+\b)|(\b\d{20}\b)|(\b\d{26}\b)|^E\D{1}\d{9}\D{2}$|^9\d{15,21}$|^91[0-9]+$|^[A-Za-z]{2}[0-9]+US$/i

I know there are already lots of answers and that this was asked a long time ago, but I don't see a single one that addresses all the possible USPS tracking numbers with a single expression.

Here is what I came up with:

((\d{4})(\s?\d{4}){4}\s?\d{2})|((\d{2})(\s?\d{3}){2}\s?\d{2})|((\D{2})(\s?\d{3}){3}\s?\D{2})

See it working here: http://regexr.com/3e61u


I'm working in an Angular2+ app and just put together a component to handle common US tracking numbers. It tests them using standard JavaScript RegExp's that I put together from this resource HERE & HERE and sets the href on an anchor tag with the tracking link URL if it's good. You don't have to be using Angular or TypeScript to easily adapt this to your application. I tested it out with different dummy numbers and seem to work dynamically so far. Please note, you can also switch out the null in the last else statement with the in-line commented url and it will send you to a Google search.

Any feedback (or if your tracking numbers don't work) please let me know I will update the answer. Thanks!

USAGE IN HTML:

<app-tracking-number [trackNum]="myTrackingNumberInput"></app-tracking-number>

COMPONENT .TS

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-tracking-number',
  templateUrl: './tracking-number.component.html',
  styleUrls: ['./tracking-number.component.scss']
})
export class TrackingNumberComponent implements OnInit {
    @Input() trackNum:string;
    trackNumHref:string = null;
    // Carrier tracking numbers patterns from https://www.iship.com/trackit/info.aspx?info=24 AND https://www.canadapost.ca/web/en/kb/details.page?article=how_to_track_a_packa&cattype=kb&cat=receiving&subcat=tracking
    isUPS:RegExp = new RegExp('^1Z[A-H,J-N,P,R-Z,0-9]{16}$');               // UPS tracking numbers usually begin with "1Z", contain 18 characters, and do not contain the letters "O", "I", or "Q".
    isFedEx:RegExp = new RegExp('^[0-9]{12}$|^[0-9]{15}$');                 // FedEx Express tracking numbers are normally 12 digits long and do not contain letters AND FedEx Ground tracking numbers are normally 15 digits long and do not contain letters.
    isUSPS:RegExp = new RegExp('^[0-9]{20,22}$|^[A-Z]{2}[0-9,A-Z]{9}US$');  // USPS Tracking numbers are normally 20-22 digits long and do not contain letters AND USPS Express Mail tracking numbers are normally 13 characters long, begin with two letters, and end with "US".
    isDHL:RegExp = new RegExp('^[0-9]{10,11}$');                            // DHL tracking numbers are normally 10 or 11 digits long and do not contain letters.
    isCAPost:RegExp = new RegExp('^[0-9]{16}$|^[A-Z]{2}[0-9]{9}[A-Z]{2}$'); // 16 numeric digits (0000 0000 0000 0000) AND 13 numeric and alphabetic characters (AA 000 000 000 AA).

    constructor() { }

    ngOnInit() {
        this.setHref();
    }

    setHref() {
        if(!this.trackNum) this.trackNumHref = null;
        else if(this.isUPS.test(this.trackNum)) this.trackNumHref = `https://wwwapps.ups.com/WebTracking/processInputRequest?AgreeToTermsAndConditions=yes&loc=en_US&tracknum=${this.trackNum}&Requester=trkinppg`;
        else if(this.isFedEx.test(this.trackNum)) this.trackNumHref = `https://www.fedex.com/apps/fedextrack/index.html?tracknumber=${this.trackNum}`;
        else if(this.isUSPS.test(this.trackNum)) this.trackNumHref = `https://tools.usps.com/go/TrackConfirmAction?tLabels=${this.trackNum}`;
        else if(this.isDHL.test(this.trackNum)) this.trackNumHref = `http://www.dhl.com/en/express/tracking.html?AWB=${this.trackNum}&brand=DHL`;
        else if(this.isCAPost.test(this.trackNum)) this.trackNumHref =`https://www.canadapost.ca/trackweb/en#/search?searchFor=${this.trackNum}`;
        else this.trackNumHref = null; // Google search as fallback... `https://www.google.com/search?q=${this.trackNum}`;
    }

}

COMPONENT .HTML

<a *ngIf="trackNumHref" [href]="trackNumHref" target="_blank">{{trackNum}}</a>
<span *ngIf="!trackNumHref">{{trackNum}}</span>

ReferenceURL : https://stackoverflow.com/questions/619977/regular-expression-patterns-for-tracking-numbers

반응형