当正则表达式正确时 Java 正则表达式问题

标签 java regex

我有一个正确的正则表达式,但在我的程序中失败了。通常,不同的眼光是好的。

相关代码:

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/

相关文章:

java - 如何使用 lambda 编写新的 ListChangeListener<Item>()?

java.io.FileNotFoundException :/mnt/sdcard/Android/data/com. example.imymemine/files/qwer/abcd.txt (是一个目录)

java - 获取异常原因、类型转换为正确类型的正确方法签名是什么?

regex - 简化 htaccess 中的重定向

Java正则表达式匹配

javascript - javascript中的转义字符,替换\"to only "

regex - R - 具有特定排除的 grepl

java - 从 HashMap 中删除条目

java - Eclipse 在创建 Maven 原型(prototype)项目时不使用最新的快照

javascript - 用新行删除大量空白