gpt4 book ai didi

Java正则表达式: finding match errors

转载 作者:行者123 更新时间:2023-12-01 13:40:55 26 4
gpt4 key购买 nike

我想知道正则表达式匹配失败时错误的确切位置。但我在 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 方法可以告诉您为什么不匹配。

如果您将其用于任何类型的(输入)验证,您必须抛出一个通用异常,例如“提供的值与预期模式不匹配 ”。

关于Java正则表达式: finding match errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com