0

I’m wondering if it’s possible to use regex to find all occurrences of a repeating string in another string

For a simple example find aaa in aaaaaaaaaaaaaaa

If I’ve counted properly it happens 13 times so an answer that finds 13 rather than 5 occourances would be good.

Another example

abcabc in abcabcabcabc where it repeats 3 times

  • 1
    Are you using a programming language here, or is this more of an abstract regex question? – Tim Biegeleisen Oct 27 '19 at 13:03
  • 1
    just enclose the pattern in a group and put a quantifier? `(abc)+` Although the *number* of repeats will not be explicitly output. Depends on where you're using it - in a programming language, you're likely to be able to match the pattern ibce until you exhaust all matches, so you'll have to keep a counter. – VLAZ Oct 27 '19 at 13:04
  • Yes @Tim I’m using Swift i was thinking the solution would be to solve this puzzle then use numberOfMatches(in:options:range:) to count the ocourances – Jason Clutterbuck Oct 28 '19 at 02:19
  • Thanks @Toto I don’t know why I didn’t find this answer in my searching. It looks like the right idea. – Jason Clutterbuck Oct 28 '19 at 02:24

2 Answers2

1

If the regex engine of your chosen programming language or tool supports positive lookaheads?
Then you could use that.

A javascript example that counts 13 "aaa" in the sample string:

var str = "aaaaaaaaaaaaaaa";
var re = /(?=(aaa))/g;

var total = str.match(re).length;
console.log(total);

An other example, which counts 3 "abcabc":

var str = "abcabcabcabc";
var searchString = "abcabc";
var re = new RegExp("(?=("+searchString+"))", "g");

var total = str.match(re).length;
console.log(total);
LukStorms
  • 28,916
  • 5
  • 31
  • 45
-1

Usually i would go for quantifiers like (aaa)+ or if you know the specific length then (aaa){5} or if you need it a minimum of 5 times then (aaa){5,} or a maximum of 5 (aaa){,5} or a minimum of 5 and maximum of 10 like this (aaa){5,10}.

If you are unsure if any matches are in there, then you can also go for "0 or more" which would be (aaa)*

As a hinter, you can match IPv4 Adresses (badly) like this:

([0-9]{1,3}\.?){4}

do not use this in production for matching IPs, this is just to illustrate a repeating pattern :)

Franz Bettag
  • 437
  • 2
  • 8