I recently did instance counting in an app to search broken .bky files for orphan component references.
The basic idea is to split the text into a list at whatever unique pattern defines what you want to find, then use the list length of the resulting temp list.