To get a line containing a character before and after each occurrence of one line in another, you can use a regex expression:
"(^|.)" + str + "(.|$)"
and then you can iterate over the groups and combine them.
This expression will search (^|.) , Either the beginning of the string ^ , or any character . followed by str , followed by (.|$) , any character . or end of line $ .
You can try something like this:
import java.util.regex.Matcher; import java.util.regex.Pattern; public String wordEnds(String str, String word){ Pattern p = Pattern.compile("(.)" + str + "(.)"); Matcher m = p.matcher(word); String result = ""; int i = 0; while(m.find()) { result += m.group(i++); } return result; }
Moishe lipsker
source share