Regex for overlapping fixed width matches -
so have string:
'aaggbb'
and want find groups of type axxxb x char. thought regex:
/(a(?:...)b)/ig
would trick, gets first one:
'aaggbb'
and misses second one:
'aaggbb'
how both?
i searched around while trying figure out hope didn't miss obvious. thanks!
if looking fixed length substrings, need specifify limiting quantifier {3}
(match 3 symbols) , use capturing inside look-ahead match substrings:
(?=(a.{3}b))
see demo
the look-ahead not consuming characters, , enable overlapping matches. "consuming" means after lookahead or lookbehind's closing parenthesis, regex engine left standing on same spot in string started looking: hasn't moved. position, engine can start matching characters again. (from rexegg.com)
var re = /(?=(a.{3}b))/g; var str = 'aaggbb'; while ((m = re.exec(str)) !== null) { if (m.index === re.lastindex) { re.lastindex++; } document.getelementbyid("demo").innerhtml += m[1] + "<br/>"; }
<div id="demo" />
Comments
Post a Comment