import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\bwith\\s+(?!\\P{P}*\\bwith\\b)(\\P{P}+)";
final String string = "This is a test with a string with punctuation, and an end. Then test words, and more text. And here whith more text with more punctuation, like that.\n\n"
+ "It should also work with a sentence finishing by a dot.\n\n"
+ "And what do we do with fruits? such as apples, pears and lemons?\n\n"
+ "Please come with this stuff:\n"
+ "- your laptop.\n"
+ "- a block of paper.\n"
+ "- a pencil.\n\n"
+ "I would not recommend sun bathing with just some oil!\n\n"
+ "I don't think you want to match \"with\" if it's in a string.";
final Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CASE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html