package yzz;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringTools
{
/**
* 将字符转义成html格式
*
* @param str
* 字符串
* @return 转换后的html
*/
public static String htmlLableExe(String str)
{
str = stringReplace(str, "<", "<");
str = stringReplace(str, ">", ">");
str = stringReplace(str, "&", "&");
return str;
}
/**
* 将html转义成字符格式
*
* @param str
* 源字符串
* @return 转换后的字符
*/
public static String charLableExe(String str)
{
str = stringReplace(str, "&", "&");
str = stringReplace(str, "<", "<");
str = stringReplace(str, ">", ">");
return str;
}
/**
* 字符串转义特殊处理
*
* @param str
* 源字符串
* @param sr
* 替换成哪个字符
* @param sdz
* 需要替换的字符
* @return 目标字符串
*/
public static String stringReplace(String str, String sr, String sd)
{
String regEx = sr;
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
str = m.replaceAll(sd);
return str;
}
/**
* 判断是否存在特殊字符
*
* @param str
* 源字符串
* @return false存在,true校验通过
*/
public static boolean htmlContains(String str)
{
if (str.contains("<") || str.contains(">") || str.contains("&"))
{
return false;
}
return true;
}
public static void main(String[] args)
{
String charlab = "y&z<z>";
String htmllab = "y&z<z>";
String htmls = StringTools.htmlLableExe(charlab);
String chars = StringTools.charLableExe(htmllab);
System.out.println(htmls);
System.out.println(chars);
System.out.println(htmlContains("<"));
}
}