会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
Ken-Cai
博客园
首页
新随笔
联系
订阅
管理
(9)正则表达式 正向预搜索、反向预搜索
正向预搜索声明格式:正声明 “(?=…)”,负声明 “(?!...)” ,声明本身不作为最终匹配结果的一部分,请看下面的示例:
Code
string
x
=
"
1024 used 2048 free
"
;
Regex r1
=
new
Regex(
@"
\d{4}(?= used)
"
);
if
(r1.Matches(x).Count
==
1
)
{
Console.WriteLine(
"
r1 match:
"
+
r1.Match(x).Value);
//
输出:1024
}
Regex r2
=
new
Regex(
@"
\d{4}(?! used)
"
);
if
(r2.Matches(x).Count
==
1
)
{
Console.WriteLine(
"
r2 match:
"
+
r2.Match(x).Value);
//
输出:2048
}
//
r1中的正声明表示必须保证在四位数字的后面必须紧跟着“ used”,r2中的负声明表示四位数字之后不能跟有“ used”。
反向预搜索声明格式:正声明“(?<=)”,负声明“(?<!)”,声明本身不作为最终匹配结果的一部分,请看下面的示例:
Code
string
x
=
"
used:1024 free:2048
"
;
Regex r1
=
new
Regex(
@"
(?<=used:)\d{4}
"
);
if
(r1.Matches(x).Count
==
1
)
{
Console.WriteLine(
"
r1 match:
"
+
r1.Match(x).Value);
//
输出:1024
}
Regex r2
=
new
Regex(
@"
(?<!used:)\d{4}
"
);
if
(r2.Matches(x).Count
==
1
)
{
Console.WriteLine(
"
r2 match:
"
+
r2.Match(x).Value);
//
输出:2048
}
//
r1中的反向正声明表示在4位数字之前必须紧跟着“used:”,r2中的反向负声明表示在4位数字之前必须紧跟着除“used:”之外的字符串。
posted @
2011-03-08 15:08
Ken-Cai
阅读(
436
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告