Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp to capture overlapping matches [duplicate]

Tags:

regex

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

like image 504
Crypto Avatar asked Sep 14 '25 18:09

Crypto


1 Answers

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
)
like image 188
anubhava Avatar answered Sep 17 '25 07:09

anubhava