(java)找非a标签的内容,是否存在关键字,有就加

 /**
     * 拆分html的内容,把xxxxx<a>xxxxx</a>xxxx这样格式的内容拆分开来
     * @param html 要解析的html文档内容
     * @return 
     */
    public static InfoSplitBean getHTMLContext(String html, String keyword, String url){
        //<a href="javascript:;">jvldsjf面试官ljsdlfkm</a>
        Pattern p = Pattern.compile("<a.*?>.*?(</a>){1}?");//匹配<a>开头
        //获取非a标签那块内容
        String[] split = p.split(html);
        
        Matcher m = p.matcher(html);//寻找a标签的内容
       //得到a标签里面那块内容
        List<String> aLabelList = new ArrayList<String>();
        Stack<String> aLabelStack = new Stack<String>();
        while (m.find()) {
        	aLabelList.add(m.group());
        }
        
        //倒序入栈
        Collections.reverse(aLabelList);
        for(String s : aLabelList){
        	aLabelStack.push(s);
        }
        
        //寻找需要替换的位置,和替换内容
        List<String> tmpList = new ArrayList<String>();
        boolean hasReplace = false;
        //拆分的时候,可能会有空的
        for(String s : split){
        	int idx = s.indexOf(keyword);
        	if(!hasReplace && idx > -1){
        		tmpList.add(s.replaceFirst(keyword, "<a href=\""+url+"\" target=\"_blank\">"+keyword+"</a>"));
        		hasReplace = true;
        	}else{
        		tmpList.add(s);
        	}
        }
        
       //倒序入栈
        Stack<String> splitStack = new Stack<String>();
        for(int i=tmpList.size()-1;i>-1;i--){
        	splitStack.push(tmpList.get(i));
        }
        
        StringBuffer sb = new StringBuffer();
        //匹配内容,考虑每次替换之后,长度会改变。
        while(!splitStack.isEmpty() || !aLabelStack.isEmpty()){
	        sb.append(!splitStack.isEmpty()?splitStack.peek():"").append(!aLabelStack.isEmpty()?aLabelStack.peek():"");
	        if(!splitStack.isEmpty()){
	        	splitStack.pop();
	        }
	        if(!aLabelStack.isEmpty()){
	        	aLabelStack.pop();
	        }
        }
        InfoSplitBean infoSplitBean = new InfoSplitBean();
        infoSplitBean.setSuccess(hasReplace);
        infoSplitBean.setContext(sb.toString());
    	return infoSplitBean;
    }


代码优化

/**
	 * @see {@link InfoAction getHTMLContext()}
	 * @param html
	 * @param keyword
	 * @param url
	 * @return
	 */
	public static JSONObject getHTMLContextOptimum(String html, String keyword, String url){
		JSONObject jsonObject = new JSONObject();
		String result = html.replaceFirst("(?i)"+keyword+"(?=[^<>]*(?:<\\w|<\\/[^a]|$))", "<a href=\""+url+"\" target=\"_blank\">"+keyword+"</a>");
		if (result.length() - html.length() > 0) {
			jsonObject.put("success", true);
		}else{
			jsonObject.put("success", false);
		}
		jsonObject.put("result", result);
		return jsonObject;
	}


转载于:https://my.oschina.net/moziqi/blog/402013

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值