Java正则表达式:查找匹配错误
我想知道正则表达式匹配失败时错误的确切位置。但我在Matcher中找不到任何类或方法,在模式中也找不到。有什么帮助吗Java正则表达式:查找匹配错误,java,regex,Java,Regex,我想知道正则表达式匹配失败时错误的确切位置。但我在Matcher中找不到任何类或方法,在模式中也找不到。有什么帮助吗 Pattern regExpPattern=Pattern.compile(“我的正则表达式”); Matcher Matcher=regExpPattern.Matcher(“输入字符串”); 如果(!matcher.matches()){ //这里有更好的错误处理 抛出新异常(“无效表达式”); } 编辑: 以下是工作代码摘录: public class FOPReques
Pattern regExpPattern=Pattern.compile(“我的正则表达式”);
Matcher Matcher=regExpPattern.Matcher(“输入字符串”);
如果(!matcher.matches()){
//这里有更好的错误处理
抛出新异常(“无效表达式”);
}
编辑:
以下是工作代码摘录:
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();
}
}
公共类前传播音员{
私有静态模式regExpPattern;
私有静态字符串requestRegexp;
私有静态字符串regexpseparator;
私有静态字符串[]输入\格式=新字符串[]{“FO”,“IFP”};
私有静态字符串[]输出格式=新字符串[]{“PDF”、“PS”、“AFP”、“IFP”};
静止的{
regexpSeparators=新字符串(“(\\Q|@\\E|=”);
requestRegexp=新字符串(“运行”+regexpSeparators+“[a-zA-Z]+.*”
+regexpSeparators+“inputFormat=(”);
对于(int i=0;i
}没有API方法可以告诉您为什么不匹配
如果将其用于任何类型的(输入)验证,则必须抛出一个通用异常,例如“提供的值与预期模式不匹配”。此解决方案有什么问题。这不是很好,但对于我的需要,它起了作用:
int index = -1;
try {
Field declaredField = Matcher.class.getDeclaredField("last");
declaredField.setAccessible(true);
index =Integer.parseInt(declaredField.get(matcher).toString()); } catch
(Exception e) { }
你能给出一个输入字符串和正则表达式的例子,它会产生一个“匹配错误”以及你想要返回的值吗?FWIW,你可以用来调试你的正则表达式,尽管你必须先将它们转换成PCRE格式(去掉双转义符,有些类Java可以处理但不能处理PCRE)。只需将字符串与regex匹配,然后单击左侧的小bug图标,我的正则表达式就可以了。它的工作,因为它应该!问题是,我想知道更多关于匹配错误的信息,比如输入字符串中发现“坏”字符的索引。我将发布完整的代码和一个简单的示例。没有找到匹配项时没有错误,只是没有匹配项。当某些内容不匹配时,它到处都“不匹配”。匹配不会在某个位置停止。