标签:
非捕获性分组语法为(?:pattern),即将pattern部分组合成一个可统一操作的组合项,但不把这部分内容当作子匹配捕获,匹配的内容部进行编号也不存储在缓冲区中供以后使用。非捕获性分组方法在必须进行组合、但又不想对组合的部分进行缓存的情况下非常有用。
例如,要在一篇英文资料中查找"program"和"project"两个单词,正则表达式可表示为/program|project/,也可表示为/pro(gram|ject)/,但是缓存子匹配(gramject)没有意义,就可以用/pro(?:gram|ject)/进行非捕获性匹配这样既可以简洁匹配又可不缓存无实际意义的字匹配。
实例:
<script type="text/javascript">
<!--
var str = "program,a good project";
var reg = /program|project/g;
var arr = reg.exec(str);
var msg;
if(arr){
msg = arr+"成功匹配<br>";
}else{
msg = "匹配失败<br>";
}
document.write(msg);
arr = reg.exec(str);
if(arr){
msg = arr+"成功匹配";
}else{
msg = "匹配失败";
}
document.write(msg);
-->
</script>
输出:
program成功匹配
project成功匹配
-----------------------------------------------------------------------------------------------------------------
实例:
<script type="text/javascript">
<!--
var str = "program,a good project";
var reg = /pro(gram|ject)/g;
var arr = reg.exec(str);
var msg;
if(arr){
msg = arr+"成功匹配<br>";
}else{
msg = "匹配失败<br>";
}
document.write(msg);
arr = reg.exec(str);
if(arr){
msg = arr+"成功匹配";
}else{
msg = "匹配失败";
}
document.write(msg);
-->
</script>
输出:
program,gram成功匹配
project,ject成功匹配
-----------------------------------------------------------------------------------------------------------------
实例:
<script type="text/javascript">
<!--
var str = "program,a good project";
var reg = /pro(?:gram|ject)/g;
var arr = reg.exec(str);
var msg;
if(arr){
msg = arr+"成功匹配<br>";
}else{
msg = "匹配失败<br>";
}
document.write(msg);
arr = reg.exec(str);
if(arr){
msg = arr+"成功匹配";
}else{
msg = "匹配失败";
}
document.write(msg);
-->
</script>
输出:
program成功匹配
project成功匹配
标签:
原文地址:http://www.cnblogs.com/yangyang63963/p/5692992.html