joost2076
joost2076

Reputation: 101

javascript regular expression repeat with group

I want to use a captured group / backreference inside a repeat ({}). This is not working probably because inside the repeat the backreference is a number inside quotes in stead of a number. Is there a way to escape the quotes ?

An example to clarify: The string is "B 2 zzzzz". I want to capture 'zz' by defining only one regex. What I tried is:

'B 2 zzzz'.match(/B (\d)+ (z{\1})/)

This returns nothing. The following

'B 2 zzzz'.match(/B (\d)+ (z{2})/) 

does work. So I am guessing that the \1 backreference is "2" in stead of 2. Is there a way to escape this ? Or another way to do this without defining to regular expressions ?

Upvotes: 0

Views: 104

Answers (1)

Toto
Toto

Reputation: 91415

I can't see a way to do it with a single regex, here is a way using 2 regex, the first one pick up the digits, the second use this value to build a new regex:

str = 'B 3 zzzzz';
num = str.match('B (\\d+) z+');
re = new RegExp('B \\d+ (z{' + num[1] + '})');
z = str.match(re);
console.log('z = '+z[1]);

Another way:

str = 'B 3 zzzz';
num = str.match('B (\\d+) (z+)');
if (num[2].length >= num[1]) {
  z = num[2].substr(0, num[1]);
  console.log('z = ' + z);
} else {
  console.log('No match');
}

Upvotes: 1

Related Questions