Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java帮助使用模式操纵锚点_Java_Regex - Fatal编程技术网

Java帮助使用模式操纵锚点

Java帮助使用模式操纵锚点,java,regex,Java,Regex,我的程序在完成一些事情时遇到了困难,我希望有人能够帮助我 我有一个字符串,其中包含HTML页面的源代码 我想做的是提取以下HTML的所有实例并将其放入数组中: <img src="http://*" alt="*" style="max-width:460px;"> 因此,我将有一个X大小的数组,其中包含与上面类似的值,显然src和alt属性已更新 这可能吗?我知道有XML解析器,但格式总是一样的 非常感谢您的帮助。当您获得ArrayIndexOutOfBoundsExcept

我的程序在完成一些事情时遇到了困难,我希望有人能够帮助我

我有一个字符串,其中包含HTML页面的源代码

我想做的是提取以下HTML的所有实例并将其放入数组中:

<img src="http://*" alt="*" style="max-width:460px;">

因此,我将有一个X大小的数组,其中包含与上面类似的值,显然src和alt属性已更新

这可能吗?我知道有XML解析器,但格式总是一样的


非常感谢您的帮助。

当您获得
ArrayIndexOutOfBoundsException
时,很可能是
字符串
数组
imageTitles
不够大,无法容纳在正则表达式搜索中找到的所有ALT实例。在这种情况下,它可能是一个零大小的数组。

我建议使用
ArrayList
而不是静态数组,因为它看起来不知道要进行多少匹配

使用REGEX for HTML也不是一个好主意,但是如果您确定标记始终使用相同的格式,那么我建议:

Pattern pattern = Pattern.compile(".*<img src=\"http://(.*)\" alt=\"(.*)\"\\s+sty.*>", Pattern.MULTILINE);
Pattern=Pattern.compile(“*”,Pattern.MULTILINE);
以下是一个例子:

public static void main(String[] args) throws Exception {
        String web;
        String result = "";
        for (int i = 0; i < 10; i++) {
            web = "<img src=\"http://image" + i +".jpg\" alt=\"Title of Image " + i + "\" style=\"max-width:460px;\">";
            result += web + "\n";
        }
        System.out.println(result);
        Pattern pattern = Pattern.compile(".*<img src=\"http://(.*)\" alt=\"(.*)\"\\s+sty.*>", Pattern.MULTILINE);

        List<String> imageSources = new ArrayList<String>();
        List<String> imageTitles = new ArrayList<String>();

        Matcher matcher = pattern.matcher(result);
        while (matcher.find()) {
            String imageSource = matcher.group(1);
            String imageTitle = matcher.group(2);
            imageSources.add(imageSource);
            imageTitles.add(imageTitle);

        }

        for(int i = 0; i < imageSources.size(); i++) {
            System.out.println("url: " + imageSources.get(i));
            System.out.println("title: " + imageTitles.get(i));

        }
    }
}
publicstaticvoidmain(字符串[]args)引发异常{
弦网;
字符串结果=”;
对于(int i=0;i<10;i++){
web=“”;
结果+=web+“\n”;
}
系统输出打印项次(结果);
Pattern=Pattern.compile(“*”,Pattern.MULTILINE);
List imageSources=new ArrayList();
List imageTitles=新建ArrayList();
Matcher Matcher=pattern.Matcher(结果);
while(matcher.find()){
字符串imageSource=matcher.group(1);
字符串imageTitle=matcher.group(2);
imageSources.add(imageSource);
imageTitles.add(imageTitle);
}
对于(int i=0;i
太棒了!这正是我想要的,并且+1用于找到同时获取src和alt值的解决方案。非常感谢你!