0

I have a pattern for a strings like "5", "54", "1/19/99", "99/88/77" - each section separated by "/" can contain number in the range of 1-99 and the amount of such parts can be from 1 to n. For that purpose I use this regular expression: /^[1-9]{1,2}(\/[1-9]{1,2})*/

I have 2 questions:

  1. This regular expression give positive test for a string like "123456". Why?
  2. Can I dynamically use n to set the max amount of parts that can be used, let's say like this:

    /^[1-9]{1,2}(\/[1-9]{1,2}){0, n}/

Daniyal Lukmanov
  • 1,079
  • 8
  • 20
  • because it matches `12` You need to specify end of string. For `n` you need to dynamically build it with `new RegExp()` – epascarello May 26 '20 at 12:41
  • 1
    You need a string termination in your regex. `123456` *begins* with a two digit number, which your regex, as it stands, matches. Try `/^[1-9]{1,2}(\/[1-9]{1,2})*$/`. The `$` indicates it should reach the end of the input after matching what came before it. And "no" to your second question. You can't parameterize `n` in `{0,n}`. The `*` you have is fine. – lurker May 26 '20 at 12:41
  • 1) You did not match the entire string, add `$` at the end. 2) Build the pattern dynamically, then you can set `n` to any value you want. See the links on top for the solutions. – Wiktor Stribiżew May 26 '20 at 12:44
  • @lurker I got the idea about the `$`. I think I'm just tired a little. Anyway thanks. About the `n` times I think I need to find some workaround. – Daniyal Lukmanov May 26 '20 at 12:45
  • Your second question could be a good topic for a separately posted question if you include a description of the context of what you need, if you continue to get stuck on that one. – lurker May 26 '20 at 12:53
  • @lurkerI found a solution for my case: `new RegExp('^[1-9]\{1,2\}(\/[1-9]\{1,2\})\{0,' + n + '\}$')` – Daniyal Lukmanov May 26 '20 at 14:07

0 Answers0