日期:2014-05-20  浏览次数:20934 次

求一正则表达式,判断字符串中是否包含非法字符
主要是不能包含键盘上数字上方的特殊符号和?等,由于不是从web而是从excel表中导入,所以无法使用js中的方法,望高手不吝赐教!谢谢

------解决方案--------------------
[^?!@#$%\^&*()]+
以上是取反字符集,不要屏蔽的字符都加到[^ ]里即可
注: ] \ ^ - 这四个字符加时需要转义,如[^ \-\^\]\\]

import java.util.regex.*;

// 表达式对象
Pattern p = Pattern.compile( "[^?!@#$%\\^&*()]+ ");

// 创建 Matcher 对象
Matcher m = p.matcher( "your string ");

// 替换
String newstring = m.replaceAll( "replace to ");
------解决方案--------------------
import java.util.regex.* ;

public class RegexTest {

public static void main(String[] args) {

String qString= "sds334232ds ";
String regx= "!|!|@|◎|#|#|(\\$)|¥|%|%|(\\^)|……|(\\&)|※|(\\*)|×|(\\()|(|(\\))|)|_|——|(\\+)|+|(\\|)|§ ";
System.out.println(hasCrossScriptRisk(qString,regx));

}

/**
* 检查输入的数据中是否有特殊字符
* @param qString 要检查的数据
* @param regx 特殊字符正则表达式
* @return boolean 如果包含正则表达式 <code> regx </code> 中定义的特殊字符,返回true;
* 否则返回false
*/
public static boolean hasCrossScriptRisk(String qString, String regx) {
if (qString!=null) {
qString = qString.trim();
Pattern p = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(qString);
return m.find();
}
return false;
}

}