日期:2014-05-17  浏览次数:20543 次

栈实现HTML和UBB的转换

之前做论坛的时候曾经傻b呵呵的用环视正则做的,原来栈就可以啊。

这个例子不实现细节,也不完成什么功能,只是说明栈可以处理前后匹配,上代码。

package com.test;

import java.util.Stack;


public class Test {
	class Node {
		int start;
		int end;
		String tagName;
	}
	/**
	 * 忽略了匹配细节,实现html解析
	 * @param html html
	 * @return
	 */
	public String ubb(String html){
		StringBuffer result = new StringBuffer();
		int pos = -1;//标记每个开始标签符号位置
		Stack<Node> tagStack = new Stack<Node>();
		int len = html.length();
		for(int i = 0; i < len; i++){
			switch(html.charAt(i)){
				case '<':
					pos = i;
				break;
				case '>':
					if(pos != -1){
						Node node = new Node();
						node.start = pos;
						node.end = i + 1;
						node.tagName = html.substring(pos + 1, i);
						if(tagStack.isEmpty() || !tagStack.peek().tagName.equals(node.tagName)){
							tagStack.push(node);
						}else{
							Node startNode = tagStack.pop();
							System.out.println(html.substring(startNode.start, i + 1));
						}
						pos = -1;
					}
				break;
			}
		}
		return result.toString();
	}
	public static void main(String[] args) throws Exception {
		System.out.println(new Test().ubb("<a><b>asdf<b><a>"));
	}
}