regex for zip-code

前端 未结 3 1715
名媛妹妹
名媛妹妹 2020-11-28 03:39

Possible Duplicate:
What is the ultimate postal code and zip regex?

I need Regex which can satisfy all my thr

3条回答
  •  孤城傲影
    2020-11-28 04:02

    For the listed three conditions only, these expressions might work also:

    ^\d{5}[-\s]?(?:\d{4})?$
    ^\[0-9]{5}[-\s]?(?:[0-9]{4})?$
    ^\[0-9]{5}[-\s]?(?:\d{4})?$
    ^\d{5}[-\s]?(?:[0-9]{4})?$
    

    Please see this demo for additional explanation.

    If we would have had unexpected additional spaces in between 5 and 4 digits or a continuous 9 digits zip code, such as:

    123451234
    12345 1234
    12345  1234
    

    this expression for instance would be a secondary option with less constraints:

    ^\d{5}([-]|\s*)?(\d{4})?$
    

    Please see this demo for additional explanation.

    RegEx Circuit

    jex.im visualizes regular expressions:

    Test

    const regex = /^\d{5}[-\s]?(?:\d{4})?$/gm;
    const str = `12345
    12345-6789
    12345 1234
    123451234
    12345 1234
    12345  1234
    1234512341
    123451`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

提交回复
热议问题