关于Regex.Replace (String, String, String,RegexOptions) 方法
今天使用这个方法碰到了一些意外,于是就查了下资料,做了些测试,发现自己以前的理解有误.
Regex.Replace (String input, String pattern, String replacement,RegexOptions) 方法
这个方法作用是用 replacement 来替换 input中符合pattern的部分,举例如下:
input: http://www.xxx.com/news/5/
replacement: /news.aspx
pattern: http://(.*?)\.*xxx.com/news/(\d+)/*
因为input 中匹配的部分为 http://www.xxx.com/news/5/,按规则我们用/news.aspx来替换.
结果为: /news.aspx
同样:
input: abcedft http://www.xxx.com/news/5/6/7YYYYY
replacement: /news.aspx
pattern: http://(.*?)\.*xxx.com/news/(\d+/)*(\d+)/*
结果为 abcedft/news.aspxYYYYY
因为input 中匹配的为 http://www.xxx.com/news/5/6/7
另外可以用$1,$2...来引用具体的匹配内容,如
input : http://www.xxx.com/news/5/
replacement: /news.aspx?c=$2
pattern: http://(.*?)\.*xxx.com/news/(\d+)/*
结果为/news.aspx?c=5
Regex.Replace (String input, String pattern, String replacement,RegexOptions) 方法
这个方法作用是用 replacement 来替换 input中符合pattern的部分,举例如下:
input: http://www.xxx.com/news/5/
replacement: /news.aspx
pattern: http://(.*?)\.*xxx.com/news/(\d+)/*
因为input 中匹配的部分为 http://www.xxx.com/news/5/,按规则我们用/news.aspx来替换.
结果为: /news.aspx
同样:
input: abcedft http://www.xxx.com/news/5/6/7YYYYY
replacement: /news.aspx
pattern: http://(.*?)\.*xxx.com/news/(\d+/)*(\d+)/*
结果为 abcedft/news.aspxYYYYY
因为input 中匹配的为 http://www.xxx.com/news/5/6/7
另外可以用$1,$2...来引用具体的匹配内容,如
input : http://www.xxx.com/news/5/
replacement: /news.aspx?c=$2
pattern: http://(.*?)\.*xxx.com/news/(\d+)/*
结果为/news.aspx?c=5