Java:如何确定正则表达式模式匹配失败的原因? [英] Java: How do I determine why a regular expression pattern match fails?

查看:72
本文介绍了Java:如何确定正则表达式模式匹配失败的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用正则表达式来匹配模式是否匹配,但是我也想知道它何时失败.

I am using a regular expression to match whether or not a pattern matches, but I also want to know when it fails.

例如,假设我的模式为"N {1,3} Y".我将其与字符串"NNNNY"匹配.我想知道它失败了,因为Ns太多了.或者,如果我将其与字符串"XNNY"匹配,我想知道它失败,因为字符串中包含无效字符"X".

For example, say I have a pattern of "N{1,3}Y". I match it against string "NNNNY". I would like to know that it failed because there were too many Ns. Or if I match it against string "XNNY", I would like to know that it failed because an invalid character "X" was in the string.

通过查看Java正则表达式包API(java.util.regex),似乎只有在匹配成功时Matcher类才能提供其他信息.

From looking at the Java regular expression package API (java.util.regex), additional information only seems to be available from the Matcher class when the match succeeds.

是否可以解决此问题?还是在这种情况下正则表达式是一种选择?

Is there a way to resolve this issue? Or is regular expression even an option in this scenario?

推荐答案

我想您应该使用解析器,而不是简单的正则表达式.

I guess you should use a parser, rather than simple regular expressions.

正则表达式可以很好地提供字符串的匹配项,但提供NON-matches却不是那么好,更不用说解释为什么匹配失败了.

Regular Expressions are good providing matches for string, but not quite so in providing NON-matches, let alone explaining why a match failed.

这篇关于Java:如何确定正则表达式模式匹配失败的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆