您的位置:首页 > 编程语言 > Java开发

过滤Java中特殊字符

2014-02-28 23:11 411 查看
过滤Java中特殊字符



/**
 * @Title:FilterString.java
 * @Package:com.you.model
 * @Description:过滤Java中特殊字符
 * @Author: 游海东
 * @date: 2014年2月28日 下午10:58:47
 * @Version V1.2.3
 */
package com.you.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @类名:FilterString
 * @描述:过滤Java中特殊字符
 * @Author:Administrator
 * @date: 2014年2月28日 下午10:58:47
 */
public class FilterString 
{
	/**
	 * 判断特殊字符
	 * @Title : FilterStr
	 * @Type : FilterString
	 * @date : 2014年2月28日 下午11:01:21
	 * @Description : 判断特殊字符
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static String FilterStr(String str) throws PatternSyntaxException
	{
		/**
		 * 特殊字符
		 */
		String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?_]";
		
        /**
         * Pattern p = Pattern.compile("a*b");
         * Matcher m = p.matcher("aaaaab");
         * boolean b = m.matches();
         */
		Pattern pat = Pattern.compile(regEx);     
        Matcher mat = pat.matcher(str);
        
        /**
         * 返回替换结果
         */
        return mat.replaceAll("").trim();  
	}

	/**
	 * @Title : main
	 * @Type : FilterString
	 * @date : 2014年2月28日 下午10:58:47
	 * @Description : 过滤字符
	 * @param args
	 */
	public static void main(String[] args) 
	{
		/**
		 * 测试字符串
		 */
		String totalStr = "~`<>?^&*()you@##%$$#^%^h^&&*&*()<>?ai@#@$~~`_+|dong?><:";
		/**
		 * 打印测试字符串
		 */
		System.out.println("打印测试字符串:" + totalStr);
		
		/**
		 * 调用过滤字符串的方法
		 */
		String filterStr = FilterStr(totalStr);
		/**
		 * 打印过滤字符串
		 */
		System.out.println("打印过滤字符串:" + filterStr);
	}

}


测试结果:



打印测试字符串:~`<>?^&*()you@##%$$#^%^h^&&*&*()<>?ai@#@$~~`_+|dong?><:
打印过滤字符串:youhaidong
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: