import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "((volume|part)|(^,)\\s?(vol|pt)[^.]+?)";
final String string = "Should Match: \n"
+ " a) Any occurences of \"Volume\" OR \"Part\" (Case Insensitive);\n"
+ " b) Any occurence of \"vol\" or \"pt\" (CI) that does not have [[comma][space] before AND [period] after;\n\n"
+ "My volume 1 \n"
+ "My name vol2.\n"
+ "My, volume 1 \n"
+ ", pt. vol2.\n\n"
+ ", part.\n"
+ ", pt.\n"
+ ", pt \n"
+ ", vol\n"
+ ". pt.\n\n"
+ "// Should match below as there is no [period] after it\n"
+ "The Red Pill, Pt 2\n"
+ ", Pt 2";
final String subst = "\\1";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
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