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

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Crypto
  • 181
  • 10

1 Answers1

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
)
anubhava
  • 761,203
  • 64
  • 569
  • 643