Regex.Replace()的用法

今天主要学了Regex.Replace 的用法以及用在哪个方面。

首先它可以替换匹配与它格式相同的主要的用在UBB以及敏感词的处理

Regex.Replace()他可以匹配任何你想要的类型

/strings = 'age=30 name=tom height=180';

//stringsl = Regex.Replace(s, @'(\w+)=(\w+)', '$2是$1');

//Console.WriteLine(sl);

//MM/DD/YYYY格式的日期转换为YYYY-MM-DD格式,

strings = '02/25/1988';

strings1 = Regex.Replace(s, '([0-9]{2})/([0-9]{2})/([0-9]{4})', '$3-$1-$2');

Console.WriteLine(s1);

$number这代表你的分组序号是哪个分组的内容

string s = 'http://www.test.com';

strings1 = Regex.Replace(s, '(^h.+m$)', '<ahref=\'$1\'>$1</a>');

Console.WriteLine(s1);

这的作用是可以将一些文本转换为超链接

$体现的分组group

$number代表的分组

·       为了防止用户用恶意代码留言,大部分论坛都不允许使用HTML语句做为回帖内容(或者进行了转义),但是这限制了用户的发挥,比如用户无法粘贴超链接、无法粘贴图片地址,无法把自己发送的文字进行加粗,改变字号。为了解决这个问题,人们设计出了UBB代码,它提供了有限的、无危害的功能,用户只要遵循代码规则就可以实现用户想要的功能。 UBB语法:http://baike.baidu.com/view/35.htm?fr=ala0_1_1

·       [URL=http://www.baidu.com]百度网[/URL]替换为<ahref='http://www.baidu.com'>百度网</a>。[img]http://www.baidu.com/a.jpg[/img]→<img>。[b]aaa[/b]→<b>aaa</b>

publicstatic void main(String[] args)

{

StringBuffer sb = new StringBuffer();

sb.append('[URL]http://www.cownew.com[/URL]\n');

sb.append('[IMG]http://www.cownew.com/pic.jpg[/IMG]\n');

sb.append('[I]Opensource![/I]\n');

sb.append('[B]important![/B]\n');

System.out.println(txUBB(sb.toString()));

}

privatestatic String txUBB(String ubb)

{

String html = ubb;

html = replace('\\[URL\\](.+)\\[/URL\\]',html,'<AHREF=$1 TARGET=_blank>$1</A>');

html =replace('\\[EMAIL\\](.+)\\[/EMAIL\\]',html,'<AHREF=mailto:$1>$1</A>');

html =replace('\\[IMG\\](.+)\\[/IMG\\]',html,'<IMGSRC=$1>');

html =replace('\\[I\\](.+)\\[/I\\]',html,'<i>$1</i>');

html =replace('\\[B\\](.+)\\[/B\\]',html,'<b>$1</b>');

return html;

}

privatestatic String replace(String regEx, String ubb, String replacement)

{

Pattern p = Pattern.compile(regEx);

Matcher m = p.matcher(ubb);

return m.replaceAll(replacement);

}

·       做一个WinForm页面,放一个多行文本框,点击按钮对文本框中的内容当作帖子进行判断。文件路径写死就行,比如c:/网站过滤词(部分).txt。做网站的难点不在页面,难点仍然是后台C#代码的编写。

·       经过查阅资料得知[\u4E00-\u9FA5]匹配所有中文字符,在判断的时候去掉所有非中文。

·       用正则表达式批量判断是否含有敏感词,IsMatch。

·       用File.ReadAllLines()、List<string>泛型简单。首先声明两个List,modList、bannedList,依次处理文件的各行,用=分割每一行,判断第二部分,如果是{MOD}就将第一部分加入modList,如果是{BANNED}就将第一部分加入bannedList。用ToArray将两个List转换为数组,然后用string.Join拼接成“安定片|罢餐|百{2}家{2}乐”,然后将“{”替换成“.{1,”,最后用IsMatch判断是否含有Banned词汇,如果是的话就禁止发帖,如果含有mod词汇,则提示需要审核。

string s = ' 坏先生@@@@@@@@@@ 亲切会见好教授,称赞他妈太牛逼了!';

stringtemp = Regex.Replace(s, @'[^\u4E00-\u9FA5]', '');

string[]lines = File.ReadAllLines(@'c:\c.txt',System.Text.Encoding.Default);

foreach(string line in lines)

{

string[]ff = line.Split('|');

if(ff[0] == 'f' &&temp.Contains(ff[1]))

{

Console.WriteLine('出现敏感词:{0}', ff[1]);

}

}

//Console.WriteLine(s1);

Console.Read();

(0)

相关推荐