another way not as optimal as using sed like proposed by Michael is
to do it via 2 tasks.
tasks 1: count the number of lines to replace (via shell module using and grep -E <regexp> | wc -l )
using register to remember the linecounted
task 2: using lineinfile and with_sequence: linecounted
one caveat is that with sequence does not accept a 0 count ( a potential future improvement ?)
so just add 1 to the count (you do not care about doing it one more time)
then you can run those 2 tasks multiples times
works for me on grub.conf