Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.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 需要使用什么正则表达式从HTML标记中提取特定值?_Java - Fatal编程技术网

Java 需要使用什么正则表达式从HTML标记中提取特定值?

Java 需要使用什么正则表达式从HTML标记中提取特定值?,java,Java,在iframe标记中,可以使用什么正则表达式来提取src属性的值?如果您指的是javascript而不是java: var iframe = document.getElementById("I1"); var src = iframe.getAttribute("src"); alert(src); //outputs the value of the src attribute 正则表达式将匹配src=“report.htm?view=country=us”,但在第一个子匹配(也是唯一的子

iframe
标记中,可以使用什么正则表达式来提取
src
属性的值?

如果您指的是javascript而不是java:

var iframe = document.getElementById("I1");
var src = iframe.getAttribute("src");
alert(src); //outputs the value of the src attribute
正则表达式将匹配
src=“report.htm?view=country=us”
,但在第一个子匹配(也是唯一的子匹配)中只能找到
之间的部分

如果只希望在iframe中匹配src属性,请执行以下操作:

<iframe.*?src="(.*?)".*?>


但在某些情况下,由于HTML固有的非规则性,这可能会失败。请参阅的顶部答案,以了解有关此问题的有趣说法。

我想说的是查看dom解析。从那里,它将与javascript答案极其相似。 Dom解析器将html转换为文档,您可以执行以下操作:

iframe=document.getElementById(“I1”);
src=iframe.getAttribute(“src”);

Regex稍微贵一点,在有其他简单的解决方案之前不要使用它,在java中试试这个

String src="<iframe name='I1' id='I1' marginwidth='1' marginheight='1'" + 
" height='430px' width='100%' border='0' frameborder='0' scrolling='no'" +
" src='report.htm?view=country=us'>";

int position1 = src.indexOf("src") + 5;
System.out.println(position1);

int position2 = src.indexOf("\'", position1);
System.out.println(position2);

System.out.println(src.substring(position1, position2));

如果您确实在使用Java(而不是JavaScript),并且只有
iframe
,则可以尝试使用正则表达式:

(?<=src=")[^"]*(?<!")

javascript而不是java?regex不应该用于解析像html文档那样复杂和复杂的东西。使用库是为了完成这类任务。可能是重复的否,我很确定他想使用java。他说他正在使用java。@djechlin我确实指出它不能解析任何html,但它会在任务中解析html我还认为,如果你能提供更好的解决方案,而不仅仅是抱怨,那么你的批评会更有建设性。指出解决方案中存在问题的评论是建设性的。它们告诉读者“这行不通”。更好的解决方案是使用HTML解析器。
134
160
report.htm?view=country=us
(?<=src=")[^"]*(?<!")
private static final Pattern REGEX_PATTERN = 
        Pattern.compile("(?<=src=\")[^\"]*(?<!\")");

public static void main(String[] args) {
    String input = "<iframe name=\"I1\" id=\"I1\" marginwidth=\"1\" marginheight=\"1\" height=\"430px\" width=\"100%\" border=\"0\" frameborder=\"0\" scrolling=\"no\" src=\"report.htm?view=country=us\">";

    System.out.println(
        REGEX_PATTERN.matcher(input).matches()
    );  // prints "false"

    Matcher matcher = REGEX_PATTERN.matcher(input);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}
report.htm?view=country=us