我想知道正则表达式匹配失败时错误的确切位置。但是我在Matcher中找不到任何可以做到这一点的类或方法。有什么帮助吗?
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");
}
修改 这是一段工作代码摘录:
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();
}
}
}
答案 0 :(得分:1)
没有API方法告诉您为什么不匹配。
如果您将此用于任何类型的(输入)验证,则必须抛出一个通用异常,例如“提供的值与预期模式不匹配&lt; put-regex-or-human-readable-pattern尤其是圆形&GT;”
答案 1 :(得分:0)
这个解决方案是什么。这不是很好,但为了我的需要,它起作用了:
int index = -1;
try {
Field declaredField = Matcher.class.getDeclaredField("last");
declaredField.setAccessible(true);
index =Integer.parseInt(declaredField.get(matcher).toString()); } catch
(Exception e) { }