4

I am looking for a regexp option or trick to capture all possible strings in a regexp when matches can overlap.

Example : /A.A/ in string "ABACADA"

It finds : ABA, ADA and not ACA !!

I would like : ABA, ACA, ADA

I am working in PHP, but it can be applied to other languages

preg_match_all('/A.A/',"ABACADA",$matches);
var_dump($matches[0]);
// output : array (size=2)
// 0 => string 'ABA' (length=3)
// 1 => string 'ADA' (length=3)

Can you help me? Thanks

3
  • 2
    just use a lookahead (?=(A.A)) see regex101.com/r/wU8uM7/18 Commented Sep 19, 2014 at 7:57
  • 1
    @AvinashRaj: That should be an answer, not a comment. Commented Sep 19, 2014 at 7:59
  • IMO lookahead is common factor but this is a PHP problem not a Python one.
    – anubhava
    Commented Feb 23, 2022 at 15:19

1 Answer 1

5

You can use a positive lookahead assertion to get all 3 matches:

(?=(A.A))

RegEx Demo

For your input it finds 3 matches in captured group #1:

  1. ABA
  2. ACA
  3. ADA

PHP Code:

if (preg_match_all('/(?=(A.A))/', "ABACADA", $m))
   print_r($m[1]); // printing index 1

Output:

Array
(
    [0] => ABA
    [1] => ACA
    [2] => ADA
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.