js 正则过滤特殊字符?

JavaScript011

js 正则过滤特殊字符?,第1张

您好

js检查是否含有非法字符,js 正则过滤特殊字符

//正则

function trimTxt(txt){

 return txt.replace(/(^\s*)|(\s*$)/g, "")

}

 

/**

 * 检查是否含有非法字符

 * @param temp_str

 * @returns {Boolean}

 */

function is_forbid(temp_str){

    temp_str=trimTxt(temp_str)

temp_str = temp_str.replace('*',"@")

temp_str = temp_str.replace('--',"@")

temp_str = temp_str.replace('/',"@")

temp_str = temp_str.replace('+',"@")

temp_str = temp_str.replace('\'',"@")

temp_str = temp_str.replace('\\',"@")

temp_str = temp_str.replace('$',"@")

temp_str = temp_str.replace('^',"@")

temp_str = temp_str.replace('.',"@")

temp_str = temp_str.replace('',"@")

temp_str = temp_str.replace('<',"@")

temp_str = temp_str.replace('>',"@")

temp_str = temp_str.replace('"',"@")

temp_str = temp_str.replace('=',"@")

temp_str = temp_str.replace('{',"@")

temp_str = temp_str.replace('}',"@")

var forbid_str=new String('@,%,~,&')

var forbid_array=new Array()

forbid_array=forbid_str.split(',')

for(i=0i<forbid_array.lengthi++){

if(temp_str.search(new RegExp(forbid_array[i])) != -1)

return false

}

return true

}

---------------------

作者:dongsir 董先生

来源:董先生的博客

原文链接:js检查是否含有非法字符

版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。转载时请标注:http://dongsir.cn/p/195

匹配两个特定字符间的内容由以下两种方法:

1.以组形式捕获

Reference:(.*?)About the author //多行模式 捕获组1

以下是java语法

String regex = "Reference:(.*?)About the author" //此为表达式

String input = ""//此为待搜索的字符串

Pattern p = Pattern.compile(regex,Pattern.DOTALL) //多行模式

Matcher matcher = p.matcher(input)

ArrayList<String>list = new ArrayList<String>()

if (matcher.find()) {

list.add(matcher.group(1)) //这个地方捕获组1

}

//  list 就是搜索的结果

如果是单行模式请注意,表达式应写为:

Reference:((.|\r\n)*?)About the author //单行模式 捕获组1

2.使用零宽断言,表达式如下:

(?<=Reference:).*?(?=About the author)

Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。

Java具有简单性、面向对象、分布式、健壮性、安全性、平台独立与可移植性、多线程、动态性等特点 。Java可以编写桌面应用程序、Web应用程序、分布式系统和嵌入式系统应用程序等。