如何将这个 Javascript 代码转换为 Java ?
2014-05-15 11:16:00 +08:00
andybest
一个 Javascript 代码的函数,其中替换的正则是 JS 语法,如何转换为 Java 语法代码?
function HTML2UBB(str) {
str = str.replace(/\r/g,"");
str = str.replace(/on(load|click|dbclick|mouseover|mousedown|mouseup)="[^"]+"/ig,"");
str = str.replace(/<script[^>]*?>([\w\W]*?)<\/script>/ig,"");
str = str.replace(/<p align=(.*)>(.*?)<\/p>/ig,"[$1]$2[\/$1]");
str = str.replace(/<a[^>]+href="([^"]+)"[^>]*>(.*?)<\/a>/ig,"[url=$1]$2[/url]");
str = str.replace(/<font[^>]+color=([^ >]+)[^>]*>(.*?)<\/font>/ig,"[color=$1]$2[/color]");
str = str.replace(/<img[^>]+src="([^"]+)"[^>]*>/ig,"[img]$1[/img]");
str = str.replace(/ /ig," ");
str = str.replace(/\n/g," ");
str = str.replace(/<\/p>/ig,"\n");
str = str.replace(/<br[^>]*>/ig,"\n");
str = str.replace(/<([\/]?)b>/ig,"[$1b]");
str = str.replace(/<([\/]?)strong>/ig,"[$1b]");
str = str.replace(/<([\/]?)u>/ig,"[$1u]");
str = str.replace(/<([\/]?)i>/ig,"[$1i]");
str = str.replace(/<([\/]?)em>/ig,"[$1i]");
str = str.replace(/<([\/]?)center>/ig,"[$1center]");
str = str.replace(/<([\/]?)pre>/ig, "[$1code]");
str = str.replace(/<([\/]?)blockquote>/ig, "[$1quote]");
//if the text mark as del, just remove it
str = str.replace(/<del[^>]*>.*<\/del>/ig, "");
str = str.replace(/&/g,"&");
str = str.replace(/ +/g," ");
str = str.replace(/\n /g,"\n");
str = str.replace(/ \n/g,"\n");
str = str.replace(/"/g,"\"");
str = str.replace(/</g,"<");
str = str.replace(/>/g,">");
str = str.replace(/<[^>]*?>/g,"");
str = str.replace(/\[url=([^\]]+)\]\n(\[img\]\1\[\/img\])\n\[\/url\]/g,"$2");
return str;
}
5 条回复
tonghuashuai
2014-05-15 11:25:05 +08:00
扔到文本编辑器里查找替换就行吧,比如所有 replace 替换成 replaceAll
andybest
2014-05-15 13:03:54 +08:00
@
tonghuashuai 谢谢,主要是正则部分,比如: str.replace(/<\/p>/ig,"\n"); 这个怎么替换成 Java 语法?
jsonline
2014-05-15 13:09:41 +08:00
这代码写的好那啥
PhilCai
2014-05-15 14:08:52 +08:00
@
andybest Java有专门正则的库,花几分钟看看就好了
tonghuashuai
2014-05-15 14:21:36 +08:00
@
andybest java 中 replaceAll 的第一个参数正则表达式就是字符串,比如"<[^>]*?>",所以剩下的就好说了,举例:
js 代码:
str = str.replace(/<[^>]*?>/g,"");
java 代码:
String str = str.replaceAll("<[^>]*?>", "")
将 /正则表达式/g 替换为 “正则表达式”,也就是将 / 和 /g 替换成 “
注意默写符号的转义
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
https://www.v2ex.com/t/112644
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.