简体   繁体   中英

Rolling Regexp in Ruby

If I have a string "ababa" how can I find all indices where the string "aba" exists? In this instance, I would want it to return 0 and 2 because I have (aba)ba and ab(aba).

EDIT: The lookahead kind of works (or it did in Ruby)... I'm now having trouble reimplementing in Javascript. This is throwing an infinite loop:

str = 'ababa',
re = /(?=aba)/g
while ((match = re.exec(str)) !== null) {
  console.log(match)
}

Thanks!

Use a lookahead instead of capturing string.

(?=aba)

Try this.See demo.

https://regex101.com/r/sJ9gM7/35

var re = /(?=aba)/g;
var str = 'ababa';
var subst = '';

var result = str.replace(re, subst);

Try this for JavaScript:

str = 'ababa',
re = /a(?=ba)/g
while ((match = re.exec(str)) !== null) {
   console.log(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