[英]Java regular expression: finding match errors
我想知道當正則表達式匹配失敗時錯誤的確切位置。 但是我在Matcher中找不到任何類或方法都無法在Pattern中做到這一點。 有什么幫助嗎?
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();
}
}
}
沒有API方法可以告訴您為什么不匹配。
如果將其用於任何形式的(輸入)驗證,則必須拋出一個通用異常,其內容為“提供的值與預期的模式<put-regex-or-human-可讀模式-here>不匹配” 。
這個解決方案是什么。 確實不是很好,但是對於我的需求卻有效:
int index = -1;
try {
Field declaredField = Matcher.class.getDeclaredField("last");
declaredField.setAccessible(true);
index =Integer.parseInt(declaredField.get(matcher).toString()); } catch
(Exception e) { }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.