正则表达式

描述字符串规则的表达式

  • /pattern/attrs
  • new RegExp(pattern,attrs)

regexObj.test(str)

  • 测试正则表达式与指定字符串是否匹配,只要包含就匹配
    <input type="text" onblur="check(this)"
    onfocus="reset(this)">
    <script>
    function check (mobileInput) {
    var value = mobileInput.value;
    if(!/^13566668888$/.test(value)){
    mobileInput.style.borderColor="red"
    };// body...
    }
    function reset (mobileInput) {
    mobileInput.style.borderColor=""
    }
    </script>

/13566668888/.test(x13566668888y);//true,只要包含字符串即正确

锚点,位置匹配

  • ^起始位置匹配
    /^http:/.test('http://163.com')
  • $结尾位置匹配
    /.jpg$/
  • \b 单词边界
    /\bis\b/.test('that is nice');//true
    /\bis\b/.test('this');//false

/^13566668888$/.test();完全符合才匹配

字符类

匹配一类字符中的一个

  • [0-9]:一个数字 [^0-9]:非数字的一个字符
    -[a-z]:一个字母 [^a-z]

  • . :任一字符,换行除外
    / ^1[0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9]$/

  • 元字符
    具有特殊意义的字符

  • ^、$、\b

  • \d:[0-9] \D:[\d]=[0-9]

  • \s:空白符 \S:[^\s]

  • \w:[A-Za-z0-9] \W:[^\w]

量词

出现的次数

  • {m,n}:m到n次
    • :{0,}
  • ?:{0,1}
  • +:{1,}

/https?/.test('https://www.163.com');//true
/https?/.test('http://www.163.com');//true
量词对前一个字符作用

手机号测试
/^1\d{10}$/

转义符

  • 需要匹配的字符是元字符,需要加转义符
    /^http:///
    /@163.com$/

多选分支

  • 或/(x|y)/=[xy]
    特殊的字符类
    /.(png|jpg|png|gif)$/
    /(.+)@(163|126|188).com$)/任意字符数@

捕获

  • 保存匹配到的字符串,日后再用
    ()捕获
    (?:)不捕获,减少内存的占用
    使用于:$1,$..., api参数或返回值
  • str.match(regexp)获取匹配正则式的字符串
    var url='https://blog.163.com/album?id=1#comment';
    var reg=(/https?:)//([/]+)(/[?])?(?[^#])?(#.)?/;
    var arr=url.match(reg);
    var protocol=arr[1];
    var host=arr[2];
    var pathname=arr[3];
    var search=arr[4];
    var hash=arr[5];

替换

  • str.replace(regexp/substr,replacement)
    替换一个子串

var ="the price of potato is 5, the price of apple is 10.";
str.replace(/(\d)+/g,'$1.00);//$1捕获的字符串存储的位置,g全局匹配

  • 通过函数,执行复杂的替换
    html代码,加入实体字符
    <script>
    var container = document.getElementById('container');

      var html = '<label>网址:</label><input placeholder="以http://起始">';
      html = html.replace(/[<>]/g, function(m0){
          switch(m0){
              case '<':
                  return '<';
              case '>':
                  return '>';
          }
      });
      console.log(html);
      container.innerHTML = html;
    </script>
    

regexpObj.exec(str)强大的检索

  • 更详尽的结果
  • 过程的状态
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 9.19--9.23 第7章 正则表达式 正则表达式是一个拆分字符串并查询相关信息的过程。 推荐练习网站: js ...
    如201608阅读 1,079评论 0 4
  • 初衷:看了很多视频、文章,最后却通通忘记了,别人的知识依旧是别人的,自己却什么都没获得。此系列文章旨在加深自己的印...
    DCbryant阅读 4,075评论 0 20
  • 一、匹配符 \:指出接着的字符为特殊字符。 ^:表示匹配的字符必须在最前边。 $:表示匹配的字符必须在最后边。 *...
    活叁黄辉冯阅读 797评论 0 3
  • 1、 出租绘本,30元/月,一次可带走4本,周期30天,逾期一天0.1元/本。 2、 出售绘本,7折出售。 3、 ...
    悦读书悦成长阅读 120评论 0 0
  • 养心的女人是一面镜子 可以照亮他人的心境,荡涤污秽的欲念,是所有人看不够的风景。如今,养眼的女人很多,养心的女人却...
    安妮007阅读 566评论 0 0