Home > OS >  Verify a string with regex in javascript
Verify a string with regex in javascript

Time:02-02

I need to accept a string that define how many ZIP code the user will use.

Examples:

  • If the user wants to use all zip codes from 1000 to 1200
    Then he will enter 1000:1200
  • If he wants to use only 1000 and 1200
    Then he will enter 1000,12000
  • combining both is possible 1010:1015,1019,1025:1027 will return [1010,1011,1012,1013,1014,1015,1019,1025,1026,1027]

I need to verify that string.
I used this to verify but it didnt work

/(\d{4}(:|,){0,1}\d{4})/gm

CodePudding user response:

You need to expand these matches after the match is found. I assume the string is validated before, if not use if (/^\d (?:[:,]\d )*$/.test(s)) { ... }.

let s = '1010:1015,1019,1025:1027';
const chunks = s.replace(/(\d ):(\d )/g, (_,$1,$2) =>
    Array.from(
        new Array(Number($2)-Number($1)), 
        (x, i) => 
            i   Number($1))
    .join(",")).split(',');
console.log(chunks);

The Array.from(new Array(Number($2)-Number($1)), (x, i) => i Number($1)) part generates a range of numbers between Group 1 and Group 2 values obtained with the /(\d ):(\d )/g regex.

CodePudding user response:

Start with a basic phrase to match either #### or ####:####:

(\d{4}(:\d{4})?)

Then extend it to match any number of them in a comma-separated list:

(\d{4}(:\d{4})?)(,(\d{4}(:\d{4})?))*

CodePudding user response:

As much as I tried to simplify a Regex, here's a true validator for your specific strings.
Looks a bit long since it matches a range 1000→1200: 1(?:[01]\d{2}|200)

/^1(?:[01]\d{2}|200)(?::1(?:[01]\d{2}|200)(?!:)|,1(?:[01]\d{2}|200))*$/g

Regex101.com example and description

Without the range
the Regex is simpler but it will also match 1201 which is not in range:

/^\d{4}(?::\d{4}(?!:)|,\d{4})*$/g

Regex101.com example and description

Simple but wrong
The simpler solution would be

/^\d{4}(?:[,:]\d{4})*$/g

Regex101.com example and description

but as you can see it will match many wrong inputs like i.e: the invalid 1000:1005:1020 (two :)

  •  Tags:  
  • Related