![](/img/trans.png)
[英]Using java regex to find img tags without a width or height attribute
[英]Regex to find all the img tags with http url
我有一个javascript正则表达式,用于从字符串中提取所有具有src
作为http://....
的<img>
标记。
regex = /<img[^>]+src="?(http:\/\/[^">]+)"?\s*\/>/g;
我的问题是如何在Java中执行此操作,其次,上述正则表达式仅给出src
的内容,我想提取整个<img>
并将其替换为空格。
PS。 可能与src一起还有许多其他属性,例如'class','alt'等。
//Try this solution:
//This answer was tested I hope it is what you're looking for :
Pattern p = Pattern.compile("<img?(.+)?\\s*\\/>");
Matcher m = p.matcher("<img src=\"http://google.com\"/>");
if(m.find())
System.out.println(m.group(1));
试试这个:
regex = /(<img[^>]+src="?http:\\/\\/[^">]+"?[^>]+\\/>)/g
它应该获取所有img标签。 (更改了正则表达式的结尾,并在img标签周围移动了括号)
请尝试以下部分
.*(<img\\s+.*src\\s*=\\s*"([^"]+)".*>).*
在这里它将创建两个匹配项。Match 1将是完整的img标签。Match 2将仅保留图像的URL。
例
package com.company;
导入java.util.regex.Matcher; 导入java.util.regex.Pattern;
公共班级主要{
public static void main(String[] args) {
String htmlFragment = "<img src='http://img01.ibnlive.in/ibnlive/uploads/2015/11/Videocon-Delite.gif' width='90' height='62'>Videocon Mobile Phones has launched three new Android smartphones - Z55 Delite, Z45 Dazzle, and Z45 Amaze with prices starting at Rs 4,599.";
Pattern pattern =
Pattern.compile( ".*(<img\\s+.*src\\s*=\\s*'([^']+)'.*>).*" );
Matcher matcher = pattern.matcher( htmlFragment );
if( matcher.matches()) {
String match = matcher.group(1);
String match1 = matcher.group(2);
//match.replaceAll("'","");
System.out.println(match);
System.out.println(match1);
//System.out.println(match2);
String newString = htmlFragment.replaceAll(match,"");
System.out.println(newString);
}
}
}
该示例使用单引号图像url,但是顶部提供的正则表达式针对您的情况使用双引号引起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.