optimize scanString to not run the regex more than once