您的位置:首页 > Web前端 > HTML

栈实现HTML和UBB的转换

2017-07-20 15:15 232 查看
之前做论坛的时候曾经傻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>"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: