【问题标题】:Android indexoutofboundsexceptionAndroid indexoutofbounds异常
【发布时间】:2014-05-05 09:39:02
【问题描述】:

大家好,我正在使用正则表达式。我有 indexoutofbounds 异常 这是我的来源

public String ExtractYoutubeURLFromHTML(String html) throws UnsupportedEncodingException
{

     Pattern pattern = Pattern.compile(this.extractionExpression);


     Matcher matcher = pattern.matcher(html);

     List<String> matches = new ArrayList<String>();
     while(matcher.find()){
         matches.add(matcher.group());
     }


    String vid0 = matches.get(0).toString();


    vid0 = vid0.replace ("\\\\u0026", "&");
    vid0 = vid0.replace ("\\\\\\", "");


    vid0=URLDecoder.decode(vid0,"UTF-8");



    return vid0;

}

我已调试并且我有 indexoutofboundsexception 无效索引异常

这部分代码有错误

 List<String> matches = new ArrayList<String>();
     while(matcher.find()){
         matches.add(matcher.group());
     }


    String vid0 = matches.get(0).toString();

我也有 C# 中的代码,我想用 java 代码重写 C# 代码 这是 C# 中的工作代码

public string ExtractYoutubeURLFromHTML(string html)
    {
        Regex rx = new Regex (this.extractionExpression);


        var video = rx.Matches (html);

        var vid0 = video [0].ToString ();

        vid0 = vid0.Replace ("\\\\u0026", "&");
        vid0 = vid0.Replace ("\\\\\\", "");

        vid0 = System.Net.WebUtility.UrlDecode (vid0);


        return vid0;

    }

【问题讨论】:

  • 您确定matches.get(0) 存在于您的代码上下文中吗?
  • @txtechhelp 是的,我确定
  • 检查您的列表,如果其中不存在任何项目,请跳过其余部分,String vid0 = matches.get(0).toString();

标签: c# java android indexoutofboundsexception


【解决方案1】:

如果matches 为空,则matches.get(0).toString(); 将给出ArrayIndexOutOfBoundsException

最好检查一下

if(matches.size()>0)
  String vid0 = matches.get(0).toString();

【讨论】:

    【解决方案2】:

    替换这个:

    String vid0 = matches.get(0).toString();
    

    通过

    if(matches.size() > 0){
    
        String vid0 = matches.get(0).toString();
    
    } else {
    
        return ""   // or you can also return null;
    
    }
    

    【讨论】:

    • 我改变了它,但现在我有 nullpointexception。我更新了我的代码
    • 请编辑您的代码。我已编辑我的答案,请再次参考并用新代码替换您的代码。
    • 我像这样更改了我的代码 if(matches.size() > 0){ vid0 = matches.get(0).toString(); } 其他 { 返回 html ; }
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多