How to Regex.scan with overlapping words?

Hello there,

I am solving the Advent of code 2024 day 4 and it explicitly asks to count overlapping words.

I am trying to solve this with regex with the following code:

defmodule AdventOfCode.DayFour.PartOne do
  alias AdventOfCode.DayFour.Input
  alias AdventOfCode.DayFour.Grid

  def solve() do
    grid = Grid.new(Input.parse())

    (Grid.vertical_lines(grid) ++
       Grid.horizontal_lines(grid) ++
       Grid.diagonal_lines(grid))
    |> Enum.map(&count_matches/1)
    |> Enum.sum()
  end

  defp count_matches(line) do
    ~r/XMAS|SAMX/
    |> Regex.scan(line)
    |> Enum.flat_map(& &1)
    |> length()
  end
end

The problem is that Regex.scan explicitly states that it only looks for non-overlapping matches:(

Assume that the Grid functions return a list of strings where each string is a line (vertical, horizontal or diagonal)

What can I do? Is there a way to match overlapping words?

Ok I’ve just learnt about “positive look aheads”
I don’t understand them fully yet but all I see is that it works, so I’ve rewrote my regex like this:

~r/(?=(XMAS|SAMX))/

And it works!