我有一个正确的正则表达式,但在我的程序中失败了。通常,不同的眼光是好的。
相关代码:
String s_mapping = ".*<MAPPING DESCRIPTION.*NAME =.*";
Pattern mapName = Pattern.compile("\"(m_.*?)\"");
String o_mapping = "";
...
if (line.matches(s_mapping)){
Matcher matcher = mapName.matcher(line);
System.out.println(line);
System.out.println(matcher);
o_mapping = matcher.group(1);
System.out.println(o_mapping);
输出
<MAPPING DESCRIPTION ="Mapping to generate the parameters file based on the parameters inserted in the table." ISVALID ="YES" NAME ="m_FAR_Gen_ParmFile" OBJECTVERSION ="1" VERSIONNUMBER ="2">
java.util.regex.Matcher[pattern="(m_.*?)" region=0,195 lastmatch=]
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: No match found
我希望最终看到 m_FAR_Gen_ParmFile
作为我的 o_mapping 输出。
当我在此站点测试时:http://www.regexplanet.com/advanced/java/index.html ,一切都过去了,一切都很好。为什么我的程序会失败?我该如何解决这个问题?
最佳答案
您需要在group()
之前调用find()
:
if (line.matches(s_mapping)){
Matcher matcher = mapName.matcher(line);
System.out.println(line);
System.out.println(matcher);
matcher.find();
o_mapping = matcher.group(1);
System.out.println(o_mapping);
来自Matcher#group()
Java文档:
Throws:
IllegalStateException - If no match has yet been attempted, or if the previous match operation failed
关于当正则表达式正确时 Java 正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25774173/