Rework to make match counting code for searches more DRY and easier to read

PR to (hopefully) address @philc 's comments on #1026, and to improve code readability.
If this can be nil, won't this cause an error on line 673, where we use it in `%=`?