昨天参加了某家公司的在线笔试,有道编程题是要用到正则表达式以及字段的截取,以前大二上Java课的时候做过一个类似的demo,没想到关键时刻居然掉链子,怎么写都只有50%的通过率,有点悲剧。
现在有博客了,就也把当年写的demo程序放上来,实现的功能是在窗体程序中输入关键词并返回该关键词在百度搜索的搜索结果数。
话说当年在CSDN博客上面有写过相关文章不知为何就谜之消失了。。
上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package web; import java.io.*; import java.net.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.applet.Applet; import java.net.*; import java.awt.*; import java.awt.event.*;
public class GetUrl extends Applet implements ActionListener { TextField keyword = new TextField(30); TextField show = new TextField(30); Choice EngineName; Button go = new Button("开始搜索");
public void init() { setBackground(Color.white); keyword = new TextField(20); show = new TextField(20); EngineName = new Choice(); EngineName.addItem("百度搜索");
EngineName.select(0); add(keyword); add(show); add(EngineName); add(go); go.addActionListener(this); }
public void actionPerformed(ActionEvent e) { if (e.getSource() == go) { try { goSearch(); } catch (Exception e1) { showStatus("搜索时发生异常:" + e1.toString()); } } }
public void goSearch() throws Exception { Graphics g = null; String str = keyword.getText(); if (str.equals("")) { showStatus("请填写搜索的关键字!"); return; } String url = "http://www.baidu.com/s?wd="; url +=URLEncoder.encode(str,"UTF-8"); URL u = new URL(url); showStatus("正在连接搜索引擎" + url);
String geturl = GetData(u); Pattern pattern = Pattern.compile("([\u76f8|\u5173|\u7ed3|\u679c|\u7ea6]{5})(.+)(\u4e2a)"); Matcher matcher = pattern.matcher(geturl); if (matcher.find( )) { showStatus("获取完毕"); show.setText(" " + matcher.group()); } else { showStatus("没有结果"); } }
public static String GetData(URL url) throws Exception{ InputStream in = url.openStream(); byte[] data = readInputStream(in); String htmldata = new String(data,"utf-8"); return htmldata; }
public static byte[] readInputStream(InputStream in) throws Exception{ ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytes; while((bytes = in.read(buffer))!= -1){ out.write(buffer,0,bytes); } in.close(); return out.toByteArray(); } }
|