What you need is String#split
as Tushar pointed out in the comment.
String s = "My cat is a cat.";
String[] res = s.split("cat");
System.out.println(Arrays.toString(res));
This is the only correct way to do it.
Now, you want to know how to match any text other than cat
with the Matcher
.
DISCLAIMER: do not use it in Java since it is highly impractical and non-performance-wise.
You may match the cat
and capture it into a Group, and add another alternative to the pattern that will match any text other than cat
.
String s = "My cat is a cat.";
Pattern pattern = Pattern.compile("(?i)(cat)|[^c]*(?:c(?!at)[^c]*)*");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
if (matcher.group(1) == null) { // Did we match "cat"?
if (!matcher.group(0).isEmpty()) // Is the match text NOT empty? System.out.println(matcher.group(0)); // Great, print it
}
}
See the IDEONE demo
Pattern details:
(?i)
- case insensitive inline modifier
(cat)
- Group 1 capturing a substring cat
|
- or
[^c]*(?:c(?!at)[^c]*)*
- a substring that is not a starting point for a cat
substring. It is an unrolled (?s)(?:(?!cat).)*
tempered greedy token.
[^c]*
- 0+ chars other than c
or C
(?:c(?!at)[^c]*)*
- zero or more sequences of:
c(?!at)
- c
or C
not followed with at
, At
, AT
, aT
[^c]*
- 0+ chars other than c
or C