简单的java正则表达式抛出illegalstateexception [英] simple java regex throwing illegalstateexception

查看:126
本文介绍了简单的java正则表达式抛出illegalstateexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图快速进行健全检查......而且它失败了。这是我的代码 -

Im trying to do a quick sanity check... and its failing. Here is my code -

import java.util.regex.*;

public class Tester {
    public static void main(String[] args) {
        String s = "a";
        Pattern p = Pattern.compile("^(a)$");
        Matcher m = p.matcher(s);
        System.out.println("group 1: " +m.group(1));
    } 
}

我期望的是看到第1组:。但相反,我得到一个 IllegalStateException:找不到匹配项,我不明白为什么。

And what I would expect is to see group 1: a. But instead I get an IllegalStateException: no match found and I have no idea why.

编辑:我也试过打印出 groupCount(),它表示有1.

I also tries printing out groupCount() and it says there is 1.

推荐答案

你需要首先调用 m.find() m.matches()才能使用 m.group

You need to invoke m.find() or m.matches() first to be able to use m.group.


  • find 可用于查找与您的模式匹配的每个子字符串(主要用于在有多个匹配的情况下)

  • 匹配将检查整个字符串是否与您的模式匹配,因此您甚至不需要添加您的模式中 ^ $

  • find can be used to find each substring that matches your pattern (used mainly in situations where there is more than one match)
  • matches will check if entire string matches your pattern so you wont even need to add ^ and $ in your pattern.

我们也可以使用 m.lookingAt()但是现在让我们跳过它的描述(你可以在文档中阅读)。

We can also use m.lookingAt() but for now lets skip its description (you can read it in documentation).

这篇关于简单的java正则表达式抛出illegalstateexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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