利用正则解析国家授时中心页面上的时间

对于程序开发来说,尤其是游戏程序开发,光光客户端的时间系统是满足不了需求的。下面利用正则解析国家授时中心网络服务器:

国家授时中心网络服务器网址为:http://www.time.ac.cn/stime.asp 。

代码如下:

	/**
	 * @author long
	 * @param args
	 */
	public static void main(String[] args) {
		
		String url = "http://www.time.ac.cn/stime.asp";
		String content = download(url);
		Pattern p1 = Pattern.compile("hrs\\s+=\\s+\\d{1,2}");
		Pattern p2 = Pattern.compile("min\\s+=\\s+\\d{1,2}");
		Pattern p3 = Pattern.compile("sec\\s+=\\s+\\d{1,2}");
		Matcher m1 = p1.matcher(content);
		Matcher m2 = p2.matcher(content);
		Matcher m3 = p3.matcher(content);
		if (m1.find()) {
			System.out.println("the hour is---->"
					+ m1.group().replace("hrs = ", ""));
		}
		if (m2.find()) {
			System.out.println("the hour is---->"
					+ m2.group().replace("min = ", ""));
		}
		if (m3.find()) {
			System.out.println("the hour is---->"
					+ m3.group().replace("sec = ", ""));
		}



/**
 * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 1.创建一个URL对象
 * 2.通过URL对象,创建一个HttpURLConnection对象 3.得到InputStram 4.从InputStream当中读取数据
 * @author long
 * @param urlStr
 * @return
 */
public static String download(String urlStr) {
	StringBuffer sb = new StringBuffer();
	String line = null;
	BufferedReader buffer = null;
	try {
		// 创建一个URL对象
		URL url = new URL(urlStr);
		// 创建一个Http连接
		HttpURLConnection urlConn = (HttpURLConnection) url
				.openConnection();
		// 使用IO流读取数据
		buffer = new BufferedReader(new InputStreamReader(
				urlConn.getInputStream()));
		while ((line = buffer.readLine()) != null) {
			sb.append(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			buffer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return sb.toString();
}
这里没有截取年月日,但是道理一样。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值