阿木申 申楠

热衷编程技术 | 申楠 : qq:38371354 | msn:amushen2005@hotmail.com

导航

.net和js中正则表达式

Posted on 2005-10-28 12:03  阿木申  阅读(1296)  评论(1)    收藏  举报
.net中
正则表达式用在字符串的匹配,查找,分割,替换,删除
主要类有:
System.Text.Regex;//正则表达式主要类
Match//匹配结果
MatchCollection//匹配结果集
例子:
class MatchingApp
{
static void Main(string[] args)
{
Regex r=new Regex("in");
Match m=r.Match("Matching");
if(m.success)
{
Console.Writeline("found '{0}' ata position {1}",m.Value,m.Index);
}
}
}
Group//一个匹配里的组
GroupCollection
Capture//捕获结果
CaptureCollection
Regex q=new Regex("(?<something>\\w+):(?<another>\\w+)");
Match n=q.Match("salary:123");
Console.writeline(n.Groups["something"].value,n.Groups["another"].Value);

常用元字符
. 除了\n以为的字符
[chars] 单个字符
[^chars] 不在列表中的单个字符
[charX-charY] 范围内的字符
\w 匹配单词字符(a-z A-Z 0-9)
\W 非单词字符
\s 匹配空白字符 \n \r \t \f
\S 非空白字符
\d 十进制数字0-9
\D 非十进制数字
^ 行首
$ 行尾
\b 在单词边界上
\B 不在单词边界上
* >=0
+ >0
? 0或1
{n} n个匹配
{n,} n个以上匹配
{n,m} n到m个匹配
() 匹配的子字符串
(?<name>) 将子字符串放进一组
| 逻辑OR