首页 > 程序开发 > 软件开发 > Java >

java正则表达式给url链接加上标签

2011-09-22

Java代码import java.util.regex.Matcher;import java.util.regex.Pattern;public class HtmlTag { public static void main(String[] args) { String str = "这是一个url链接http://www-test.co...

Java代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlTag {
public static void main(String[] args) {
String str = "这是一个url链接http://www-test.company.com/view/1_2.html?a=%B8&f=%E4+%D3#td需要转化成可点击";
String regex = "(http:|https:)//[^[A-Za-z0-9\\._\\?%&+\\-=/#]]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
StringBuffer replace = new StringBuffer();
replace.append("<a href=\"").append(matcher.group());
replace.append("\" target=\"_blank\">点击打开链接</a>");
matcher.appendReplacement(result, replace.toString());
}
matcher.appendTail(result);
System.out.println(str);
System.out.println(result);
}
}

作者“wsy495”

相关文章
最新文章
热点推荐