【问题标题】:Attempting to get data from various groups in the regex fails尝试从正则表达式中的各个组获取数据失败
【发布时间】:2013-11-17 06:27:28
【问题描述】:

我有以下正则表达式来查找字符串中的电子邮件(字符串中可能有 0 或多个电子邮件)。该表达式有 4 个组,其中一些可以匹配空值:

RegexPlanet Test 表示:

          ([-A-Za-z0-9._!#$%^&*|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{2,3}[\\.][a-z]{2,3})|([A-Za-z0-9.!#$%^&*|{}\"~`]+@[a-z0-9_-]+[\\.][a-z]{4})|([A-Z.a-z0-9!#$%^&*|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{3})|([A-Za-z0-9.!#$%^&*_-|{}'~`]+@[a-z0-9_-]+[\\.][a-z]{2})

从匹配器读取数据的代码在matchValue=matcher.group(i);处显示ArrayOutOfBoundsException

   ArrayList<String> result=new ArrayList<String>();
    Pattern pattern=Pattern.compile(regex);
    Matcher matcher=pattern.matcher(input);
    Log.d(TAG,"input: "+input);
    while(matcher.find())
    {
        String matchValue=null;
        for(int i=1;i<5;i++)
        {
            matchValue=matcher.group(i);
            if(matchValue!=null && !matchValue.equals(""))
            {    
                Log.d(TAG, "Group no: "+i+" Value: "+matchValue+" adding to result");
                result.add(matchValue);
            }
            else
            {
                Log.d(TAG, "Nothing matched for group i");
            }
        }    
    }
    return result;
}

代码有问题还是其他问题的副作用?

提前感谢您的宝贵建议

【问题讨论】:

    标签: java regex indexoutofboundsexception regex-group


    【解决方案1】:

    你知道是什么输入导致了异常吗? 一般来说,为避免此异常,您可以将 for 循环重写为:

    for(int i=1;i<=matcher.groupCount();i++)
            {....}
    

    【讨论】:

      【解决方案2】:

      试试这个:

      for(int i=1; i <= matcher.groupCount(); i++)
      {
          matchValue=matcher.group(i);
          ...
      

      我不知道为什么你的代码会有问题,它似乎正好有四个组,所以for(int i=1; i&lt;5; 似乎是正确的。但最好让匹配器告诉你计数是多少。

      【讨论】:

      • 对不起,我和user1631616同时写了:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      相关资源
      最近更新 更多