正则规则,match,exec,test区别

<script>
//var re=new RegExp('B','i');//i忽略大小写
//var re=/B/i;//方法二
var str='aBc23ad 56aa7e99 s34f';
var re=/d+/g;  //d找数字
alert(str.search(re));//找第一个数字的位置
alert(str.match(re));//把所有匹配的东西提取出来23,56,7,99,34

var re=/a/g;
alert(str.replace(re,'*'));

var re=/d/g;
alert(str.search(re))//
alert(str.match(re))//  2,3,5,6,7,9,9,3,4


// d  数字            [0-9]
// w大小写英文、数字、下划线  [a-z0-9_]
// s  空白字符
//  D               [^0-9]
//  W               [^a-z0-9_]
//  S               非空白字符
// d+  选若干数字
// g  找出全部
// [abc]间括号  任选其一 
// [^a] 方括号里时排除a
//  ^  行首      /^w/
//  $  行尾      /[a-z]$/
//  . 任意字符
//  {n} 正好出现n次
//  {n,m} 最少n次,最多m次
//  {n,} 最少n次,最多不限
//  +  {1,}
//  ?  {0,1}  可有可无
//  *  {0,}  最少最多不限
</script>
 
 
 
<script>
str='123.jpg456.png'
console.log(getFileExtendingName(str))  //.png
function getFileExtendingName(filename){
  // 文件扩展名匹配正则
  var reg = /.[^.]+$/
  var matches = reg.exec(filename)
  console.log(matches)//[".png", index: 10, input: "123.jpg456.png", groups: undefined]
  console.log(filename.match(reg))//[".png", index: 10, input: "123.jpg456.png", groups: undefined]
  if (matches) {
    return matches[0]
  }
  return ''
}

var str2='aBc23ad 56aa7e99 s34f';
var re=/d+/g;  //d找数字
console.log(str.match(re))// ["123", "456"]
console.log(str2.match(re))//["23", "56", "7", "99", "34"]
console.log(re.exec(str2))//["23", index: 3, input: "aBc23ad 56aa7e99 s34f", groups: undefined]
console.log(re.test(str2))//true
</script>
 
原文地址:https://www.cnblogs.com/hellofangfang/p/14944311.html