Been a while since I posted but I thought this would be a good little piece of code to give you the index of an exact word in a large string. I found the need in this because I was parsing command-line output.
Pattern pattern = Pattern.compile("\\bbe\\b"); Matcher matcher = pattern.matcher("Today is a good day because I will be going to the park."); if(!matcher.find()) { return -1; } int index = matcher.start();
The result will ensure not to give you the index of 'be' in because and actually give you the exact 'be' in the String. If not found, return -1. Hope this helps!
No comments:
Post a Comment