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.