I want to know the exact position of an error when a regular expression match has failed. But I couldn't find any class or method in Matcher neither in Pattern that can do that. Any help?
Pattern regExpPattern = Pattern.compile("My regular expression");
Matcher matcher = regExpPattern.matcher("Input string");
if (!matcher.matches()) {
// Better error handling here
throw new Exception("Invalid expression");
}
EDIT: Here is a working code excerpt:
public class FOPRequestParser {
private static Pattern regExpPattern;
private static String requestRegexp;
private static String regexpSeparators;
private static String[] INPUT_FORMATS = new String[] {"FO", "IFP"};
private static String[] OUTPUT_FORMATS = new String[] {"PDF", "PS", "AFP", "IFP"};
static {
regexpSeparators = new String("(\\Q|@|\\E|=)");
requestRegexp = new String("run" + regexpSeparators + "[a-zA-Z]+.*"
+ regexpSeparators + "inputFormat=(");
for (int i = 0; i < INPUT_FORMATS.length; ++i) {
requestRegexp += INPUT_FORMATS[i];
if (i != INPUT_FORMATS.length - 1) {
requestRegexp += "|";
}
}
requestRegexp += ")" + regexpSeparators + "[a-zA-Z]+.*"
+ regexpSeparators + "outputFormat=(";
for (int i = 0; i < OUTPUT_FORMATS.length; ++i) {
requestRegexp += OUTPUT_FORMATS[i];
if (i != OUTPUT_FORMATS.length - 1) {
requestRegexp += "|";
}
}
requestRegexp += ")";
}
public FOPRequestParser() {
regExpPattern = Pattern.compile(requestRegexp);
}
public void processRequest(String request) throws Exception {
Matcher matcher = regExpPattern.matcher(request);
if (!matcher.matches()) {
throw new Exception("Invalid expression");
}
}
public static void main(String[] args) {
FOPRequestParser conversion = new FOPRequestParser();
try {
String exp1 = new String("run|@|" +
"c:\\input_file.fo|@|" +
"inputFormat=FO|@|" +
"c:\\output_file.pdf|@|" +
"outputFormat=PDF");
conversion.processRequest(exp1);
System.out.println("Valid expression");
} catch (Exception e) {
e.printStackTrace();
}
}
}