An algorithm (or regular expression) needed to search for multiple instances of something

I'm not sure if there is an easy way to do this, but is there a way to find multiple instances in an unknown string? For instance:

hellohellohellobyebyebyehello

Without knowing the meaning of the above line, can I return something that will tell me that there are 3 instances of "hello" and 3 instances of "bye" (I'm not worried about the last greeting, m is looking for a consistent repeat. Thanks in advance!

+5
source share
5 answers

"testhellohellohellobyebyebyehello".match(/(.+)\1+/)

This says: "Match a sequence of at least 1 character (.+), then indicate that the first thing we found \1is at least once +or more.

["hellohellohello", "hello"], , hellohellohello ( 0), "hello" 1 (, \1).

:
- "hahahaha" ["hahahaha", "haha"] ["hahahaha", "ha"]. , .

+2
+7
s = "hellohellohellobyebyebyehello"
s.replace(/(.+)(\1+)/g, function($0, $1) {
    console.log($1 + " repeated " + ($0.length / $1.length) + " times");
});
+4

If you are looking for vocabulary words, you can load your vocabulary into the entity tree, then look at the characters in your string one by one and go through your tree. Each time you reach a leaf, you increase by one the associated "word".

0
source
var source = "asdhellohellohellobyehellohellohellohelloasdhello";
var key = "hello";
var len = key.length;
var res = 0, tempres, next;
var last = source.indexOf(key);
while(last != -1)
{
  tempres = 0;
  next = last;
  while(true)
  {
    tempres++;
    next += len;
    last = source.indexOf(key, next);
    if(last != next)
      break;
  }
  res = (tempres > res) ? tempres : res;
}
console.log(res);//4
0
source

All Articles