正则的捕获组

2017-10-12  本文已影响0人  Love小六六
 var text = "this has been a short summer";
 var pattern = /(..)or(.)/g;
  if (pattern.test(text)){
      alert(RegExp.$1);       //sh
      alert(RegExp.$2);       //t
  }

如上代码意思为找到'or'字符串,$1为匹配处的前两位字符,$2为匹配处的后1位字符

var text = "this has been a short summer";
var pattern = /(.*)as(.*)or(.*)/g;
if (pattern.test(text)){
    alert(RegExp.$1);       //this h
    alert(RegExp.$2);       // been a sh
    alert(RegExp.$3);      //t summer
}
var text = "this has been a short summer";
var pattern = /(.)hort/g;
 if (pattern.test(text)){
    alert(RegExp.input); // this has been a short summer
    alert(RegExp.leftContext);// this has been a
    alert(RegExp.rightContext);//  summer
    alert(RegExp.lastMatch);// short
    alert(RegExp.lastParen);// s
    alert(RegExp.multiline);// false
}
if (pattern.test(text)){
    alert(RegExp.$_);// this has been a short summer
    alert(RegExp["$`"]);// this has been a
    alert(RegExp["$'"]);//  summer
    alert(RegExp["$&"]);// short
    alert(RegExp["$+"]);// s
    alert(RegExp["$*"]);// false
上一篇下一篇

猜你喜欢

热点阅读