简体   繁体   中英

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 ?

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'); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM