当前位置: 代码网 > it编程>编程语言>正则表达式 > 字符串过滤正则表达式的方法

字符串过滤正则表达式的方法

2024年05月15日 正则表达式 我要评论
// 过滤特殊字符 public staticstring stringfilter(string str) throws patternsyntaxexception {// 只允许字母和数字 //

// 过滤特殊字符 public staticstring stringfilter(string str) throws patternsyntaxexception {
// 只允许字母和数字 // string regex ="[^a-za-z0-9]";
// 清除掉所有特殊字符

string regex="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“'。,、?]"; 
pattern p = pattern.compile(regex); 
matcher m = p.matcher(str);
return m.replaceall("").trim();
} 
@test public void teststringfilter() throws patternsyntaxexception {
string str = "*adcvs*34_a _09_b5*[/435^*&城池()^$$&*).{}+.|.)%%*(*.中国}34{45[]12.fd'*&999下面是中文的字符¥……{}【】。,;'“‘”?"; 
system.out.println(str); 
system.out.println(stringfilter(str));
}

用的是junit测试的,当然你可以改成main

java正则表达式学习:

因为正则表达式是一个很庞杂的体系,此例仅举些入门的概念,更多的请参阅相关书籍及自行摸索。

\\ 反斜杠
\t 间隔 ('\u0009')
\n 换行 ('\u000a')
\r 回车 ('\u000d')
\d 数字等价于[0-9]
\d 非数字等价于[^0-9]
\s 空白符号 [\t\n\x0b\f\r]
\s 非空白符号 [^\t\n\x0b\f\r]
\w 单独字符 [a-za-z_0-9]
\w 非单独字符 [^a-za-z_0-9]
\f 换页符
\e escape
\b 一个单词的边界
\b 一个非单词的边界
\g 前一个匹配的结束
^为限制开头
^java 条件限制为以java为开头字符
$为限制结尾
java$ 条件限制为以java为结尾字符
. 条件限制除\n以外任意一个单独字符
java.. 条件限制为java后除换行外任意两个字符
加入特定限制条件「[]」
[a-z] 条件限制在小写a to z范围中一个字符
[a-z] 条件限制在大写a to z范围中一个字符
[a-za-z] 条件限制在小写a to z或大写a to z范围中一个字符
[0-9] 条件限制在小写0 to 9范围中一个字符
[0-9a-z] 条件限制在小写0 to 9或a to z范围中一个字符
[0-9[a-z]] 条件限制在小写0 to 9或a to z范围中一个字符(交集)
[]中加入^后加再次限制条件「[^]」
[^a-z] 条件限制在非小写a to z范围中一个字符
[^a-z] 条件限制在非大写a to z范围中一个字符
[^a-za-z] 条件限制在非小写a to z或大写a to z范围中一个字符
[^0-9] 条件限制在非小写0 to 9范围中一个字符
[^0-9a-z] 条件限制在非小写0 to 9或a to z范围中一个字符
[^0-9[a-z]] 条件限制在非小写0 to 9或a to z范围中一个字符(交集)
在限制条件为特定字符出现0次以上时,可以使用「*」
j* 0个以上j
.* 0个以上任意字符
j.*d j与d之间0个以上任意字符
在限制条件为特定字符出现1次以上时,可以使用「+」
j+ 1个以上j
.+ 1个以上任意字符
j.+d j与d之间1个以上任意字符
在限制条件为特定字符出现有0或1次以上时,可以使用「?」
ja? j或者ja出现
限制为连续出现指定次数字符「{a}」
j{2} jj
j{3} jjj
文字a个以上,并且「{a,}」
j{3,} jjj,jjjj,jjjjj,???(3次以上j并存)
文字个以上,b个以下「{a,b}」
j{3,5} jjj或jjjj或jjjjj
两者取一「|」
j|a j或a
java|hello java或hello
「()」中规定一个组合类型
比如,我查询<ahref=\"index.html\">index</a>中<ahref></a>间的数据,可写作<a.*href=\".*\">(.+?)</a>
在使用pattern.compile函数时,可以加入控制正则表达式的匹配行为的参数:
pattern pattern.compile(string regex, int flag)
flag的取值范围如下:

pattern.canon_eq 当且仅当两个字符的"正规分解(canonical decomposition)“都完全相同的情况下,才认定匹配。比如用了这个标志之后,表达式"a\u030a"会匹配”?"。默认情况下,不考虑"规范相等性(canonicalequivalence)"。

pattern.case_insensitive(?i) 默认情况下,大小写不明感的匹配只适用于us-ascii字符集。这个标志能让表达式忽略大小写进行匹配。要想对unicode字符进行大小不明感的匹配,只要将unicode_case与这个标志合起来就行了。

pattern.comments(?x) 在这种模式下,匹配时会忽略(正则表达式里的)空格字符(译者注:不是指表达式里的"\s",而是指表达式里的空格,tab,回车之类)。注释从#开始,一直到这行结束。可以通过嵌入式的标志来启用unix行模式。

pattern.dotall(?s) 在这种模式下,表达式’.‘可以匹配任意字符,包括表示一行的结束符。默认情况下,表达式’.'不匹配行的结束符。

pattern.multiline

(?m) 在这种模式下,’^‘和’katex parse error: expected group after '^' at position 19: …匹配一行的开始和结束。此外,'^̲'仍然匹配字符串的开始,''也匹配字符串的结束。默认情况下,这两个表达式仅仅匹配字符串的开始和结束。

pattern.unicode_case

(?u) 在这个模式下,如果你还启用了case_insensitive标志,那么它会对unicode字符进行大小写不明感的匹配。默认情况下,大小写不敏感的匹配只适用于us-ascii字符集。

pattern.unix_lines(?d) 在这个模式下,只有’\n’才被认作一行的中止,并且与’.’,’^’,以及’$'进行匹配。

抛开空泛的概念,下面写出几个简单的java正则用例:

◆比如,在字符串包含验证时

//查找以java开头,任意结尾的字符串

pattern pattern = pattern.compile("^java.*");
matcher matcher = pattern.matcher("java不是人");
boolean b= matcher.matches();

//当条件满足时,将返回true,否则返回false

system.out.println(b);

◆以多条件分割字符串时

pattern pattern = pattern.compile("[, |]+");
string[] strs = pattern.split("java hello worldjava,hello,,world|sun");
for (int i=0;i<strs.length;i++) {
system.out.println(strs[i]);
}

◆文字替换(首次出现字符)

pattern pattern = pattern.compile("正则表达式");
matcher matcher = pattern.matcher("正则表达式 hello world,正则表达式 hello world");

//替换第一个符合正则的数据

system.out.println(matcher.replacefirst(“java”));

◆文字替换(全部)

pattern pattern = pattern.compile(“正则表达式”);

matcher matcher = pattern.matcher(“正则表达式 hello world,正则表达式 hello world”);

//替换第一个符合正则的数据

system.out.println(matcher.replaceall(“java”));

◆文字替换(置换字符)

pattern pattern = pattern.compile("正则表达式");
matcher matcher = pattern.matcher("正则表达式 hello world,正则表达式 hello world ");
stringbuffer sbr = new stringbuffer();
while (matcher.find()) {
matcher.appendreplacement(sbr, "java");
}
matcher.appendtail(sbr);
system.out.println(sbr.tostring());
◆验证是否为邮箱地址
string str="ceponline@yahoo.com.cn";
pattern pattern =pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",pattern.case_insensitive);
matcher matcher = pattern.matcher(str);
system.out.println(matcher.matches());

◆去除html标记

pattern pattern = pattern.compile("<.+?>",pattern.dotall);
matcher matcher = pattern.matcher("<ahref=\"index.html\">主页</a>");
string string = matcher.replaceall("");
system.out.println(string);

◆查找html中对应条件字符串

pattern pattern = pattern.compile("href=\"(.+?)\"");
matcher matcher = pattern.matcher("<ahref=\"index.html\">主页</a>");
if(matcher.find())
system.out.println(matcher.group(1));
}

◆截取http://地址

//截取url

pattern pattern =pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
matcher matcher =pattern.matcher("dsdsds<http://dsds//gfgffdfd>fdf");
stringbuffer buffer = new stringbuffer();
while(matcher.find()){
buffer.append(matcher.group());
buffer.append("\r\n");
system.out.println(buffer.tostring());
}

◆替换指定{}中文字

string str = "java目前的发展史是由{0}年-{1}年";
string[][] object={new string[]{"\\{0\\}","1995"},newstring[]{"\\{1\\}","2007"}};
system.out.println(replace(str,object));
public static string replace(final string sourcestring,object[] object) {
string temp=sourcestring;
for(int i=0;i<object.length;i++){
string[] result=(string[])object[i];
pattern pattern = pattern.compile(result[0]);
matcher matcher = pattern.matcher(temp);
temp=matcher.replaceall(result[1]);
}
return temp;
}

◆以正则条件查询指定目录下文件

//用于缓存文件列表

private arraylist files = new arraylist();
//用于承载文件路径
private string _path;
//用于承载未合并的正则公式
private string _regexp;
class myfilefilter implements filefilter {
/**
* 匹配文件名称
*/
public boolean accept(file file) {
try {
pattern pattern = pattern.compile(_regexp);
matcher match = pattern.matcher(file.getname());
return match.matches();
} catch (exception e) {
return true;
}
}
}
/**
* 解析输入流
* @param inputs
*/
filesanalyze (string path,string regexp){
getfilename(path,regexp);
}
/**
* 分析文件名并加入files
* @param input
*/
private void getfilename(string path,string regexp) {
//目录
_path=path;
_regexp=regexp;
file directory = new file(_path);
file[] filesfile = directory.listfiles(new myfilefilter());
if (filesfile == null) return;
for (int j = 0; j < filesfile.length; j++) {
files.add(filesfile[j]);
}
return;
}

/**

显示输出信息

* @param out
*/
public void print (printstream out) {
iterator elements = files.iterator();
while (elements.hasnext()) {
file file=(file) elements.next();
out.println(file.getpath());
}
}
public static void output(string path,string regexp) {
filesanalyze filegroup1 = new filesanalyze(path,regexp);
filegroup1.print(system.out);
}
public static void main (string[] args) {
output("c:\\","[a-z|.]*");
}

到此这篇关于字符串过滤正则表达式的文章就介绍到这了,更多相关字符串过滤正则表达式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com