String template = "[chicken]"; String pattern = "\\G(?<!\\[)(\\w+)(?!\\])"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(template); while (m.find()) { System.out.println(m.group()); }
It uses a combination of negative outlook and negative outlook and >
(?<!\\[)
(check out the following changes for clarification)
EDIT 1:
If you need to take into account situations such as:
"chicken [chicken] chicken [chicken]"
We can replace the regular expression with:
String regex = "(?<!\\[)\\b(\\w+)\\b(?!\\])";
EDIT 2:
If you also need to consider situations such as:
"[chicken" "chicken]"
As in one, "chicken" is still required, you can use:
String pattern = "(?<!\\[)?\\b(\\w+)\\b(?!\\])|(?<!\\[)\\b(\\w+)\\b(?!\\])?";
In fact, these are two cases where there is only one bracket on both sides. He accomplishes this through | that acts like a or, and using ? after waiting / lag, where ? means 0 or 1 of the previous expression.
source share