2

To validate some fields in my forms, I need to find the number of tokens specified by a particular regular expression, as well as the length of the matches specified by that regex. For instance,

  1. With pattern [0-9]{3},[0-9]{2}, I need to find 5 for length and 2 for number of tokens.
  2. With pattern [0-9]{2}/[0-9]{2}/[0-9]{4}, I need to find 8 for length and 3 for number of tokens.

Can anyone point a direction to do this?

zx81
  • 41,100
  • 9
  • 89
  • 105
Kleber Mota
  • 8,521
  • 31
  • 94
  • 188

1 Answers1

1

Although you did not ask to solve this with regex, we will. A regex operating on a regex! Is that regex-square?

At first blush, the task sounds complex. Do we need to write a regex engine to parse your exprssions?

Fortunately, if your quantifiers are all inside {curlies}, there is a simple solution. If we match all the numbers between curlies, the number of matches will be the number of tokens, and the length will be the sum of the matches.

Our simple Regex

{(\d+)}

Okay, but how do we implement this in code?

Here is a complete script that outputs the number of tokens and the length. See the result of the online demo.

<script>
var subject = '[0-9]{2}/[0-9]{2}/[0-9]{4}';
var regex = /{(\d+)}/g;
var group1Caps = [];
var match = regex.exec(subject);

// Place Group 1 captures in an array
while (match != null) {
    if( match[1] != null ) group1Caps.push(match[1]);
    match = regex.exec(subject);
}

// How many tokens are there?
document.write("*** Number of Tokens ***<br>");
document.write(group1Caps.length);

// What length are the expected matches?
var counter = 0;
document.write("<br>*** Length of Expected Matches ***<br>");
if (group1Caps.length > 0) {
   for (key in group1Caps) counter += parseInt(group1Caps[key]);
   }
document.write(counter,"<br>")   
</script>
zx81
  • 41,100
  • 9
  • 89
  • 105