类Java PHP输出中的正则表达式
计划是这样的类Java PHP输出中的正则表达式,java,regex,Java,Regex,计划是这样的 从weburl的html页面获取源代码,例如 使用模式进行搜索,例如查找链接 按正确的显示顺序获取结果的哈希图/列表 在PHP中,制作非常简单,但在我看来,使用本机Java是不可能的 它在PHP中的外观: <?php //the html code, maybe multilined $htmlCode = file_get_contents("https://stackoverflow.com"); $replacement = Array("\n", "\cr", "\
<?php
//the html code, maybe multilined
$htmlCode = file_get_contents("https://stackoverflow.com");
$replacement = Array("\n", "\cr", "\r", "\c", "\t");
//to make it single lined like a long string
$htmlCode = str_replace($replacement, "", $htmlCode);
//Regex part
$pattern = '#<a href="(.*)">.*</a>#siU';
preg_match_all($pattern, $htmlCode, $results, PREG_SET_ORDER);
//Print it out
echo "<pre>Results: ".print_r($results,true)."</pre>";
?>
结果如下:
数组=([0]=“”,[1]=“”,…)
如何在Java中实现同样的功能
(我已经用我自己的方式试过了,我想它是如何工作的,但我认为这太夸张了。是用JerichoHTMLParser做的。)
Init.java
uc.getInputStream();
package test.java.regex;
导入java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入net.htmlparser.jericho.*;
导入java.net。*;
导入java.io.*;
导入java.util.*;
导入java.util.regex.*;
公共类init扩展了JFrame{
私人JLabel-lblKeyword;
私有JTextField关键字;
私有JButton exec;
私人JScrollPane sp;
私有区域输出;
私有模式;
私人匹配器匹配器;
private static final String thePATTERN=“是的,它可能会做得更短,但让我们从该代码开始,因为它就快到了
boolean matches = matcher.matches();
if (matches) {
this.output.setText( "found" );
}
当然可以删除,因为它是获取和使用下一行
while (matcher.find()) {
output.setText(matcher.group(1));
// Or something different, as this keeps only the last one found.
}
有一个错误:在java中。match
要求整个字符串都匹配
我也不了解来源
人们可以像你一样在ByteArrayoutPuttStream中读取所有内容
您可以使用ISO-8859-1,因为这不会编码页面不在UTF-8中时UTF-8可能会遇到的错误。现在这种情况几乎每天发生一次。goes…Regex不是最好的工具。您是否尝试过使用适当的HTML解析器,比如Jsoup?
while (matcher.find()) {
output.setText(matcher.group(1));
// Or something different, as this keeps only the last one found.
}
String st = new String(baos.toByteArray(), StandardCharsets.ISO_8859_1);