I am interested in finding 7 words in a string.
These should appear in order separated by space.
Assuming that String regex has a string with the 7 words, I was interested if a match did not occur to reduce to 6,5,4 etc words.
A first regex I thought was:
\\b(?:word1(\\s+)word2(\\s+)word3(\\s+)word4(\\s+)word5(\\s+)word6(\\s+)word7)\\b
- The above would occur by using a
StringBufferand after
splittingthe variableregexby space, I would construct the
regular expression byappend. - If I got no match I would loop again contructing the expression up
toword6etc and further reducing toword5etc until I hit a match.
I am not sure I really like this approach.Can I improve it or do it in a more efficient way?
the greedy (default) will do what you want
this will first attempt to match everything and then leave off
word7then leave offword6…