Вопрос

helo everyone i working Regex. i have indexoutofboundsexception this is a my source

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;

}

i debuged and i have indexoutofboundsexception invalid index exception

error is in this part of code

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


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

also i have woring code in C# and i want to rewrite C# code in java Code this is a working code in 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;

    }
Это было полезно?

Решение 2

Replace this one :

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

by

if(matches.size() > 0){

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

} else {

    return ""   // or you can also return null;

}

Другие советы

If matches is empty then matches.get(0).toString(); will give an ArrayIndexOutOfBoundsException.

Better check like

if(matches.size()>0)
  String vid0 = matches.get(0).toString();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top