美文网首页正则表达式
JS正则表达式浅析

JS正则表达式浅析

作者: 带马界的神秘人 | 来源:发表于2018-05-10 23:05 被阅读0次

格式校验功能

正则里的()[]

圆括号()表示一组 里面的字符是一种组合的形式
方括号[]表示一系列 里面的字符任意出现就可以
123重复三次

/(123){3}/.test('123123123'); // true
/(123){3}/.test('123123124'); // false

abc字符出现三次 aab aac 或者 abc ccc

/[abc]{3}/.test('abc'); // true
/[abc]{3}/.test('aaa'); // true
/[abc]{3}/.test('aa1'); // false

开始字符和结束字符

^ 开始字符 只有出现在正则表达式的第一个位置表示开始字符 其它位置就是表示它自身

/^a/.test('a1111'); // true
/^a/.test('baaa'); // false
/^^/.test('^1111'); //  true;
/^^/.test('b^^^');  // false;

$ 结束字符 只有出现在正则表达式的最后一个位置表示结束字符 其它位置就是表示它自身

/a$/.test('111a'); // true
/a$/.test('aaab'); // false
/$$/.test('111$'); //  true;
/$$/.test('$$$b');  // false;

组合校验

不出现某些字符表示通过校验。[]^的组合 [^]表示不出现某些字符

/^[^a-f]*$/.test('gghj'); // true 字符串从开始到结束都没有出现a到f这些字符
/^[^a-f]*$/.test('ggazz'); // false 出现了a

或的校验 满足一种就可以通过校验 |

/(123)|(456)/.test('456'); // true
/(123)|(456)/.test('123'); // true
/(123)|(456)/.test('124'); // false

/(?:z|f)ood/.test('zood'); // true
/(?:z|f)ood/.test('food'); // true
/(?:z|f)ood/.test('dood'); // false

字符提取功能

通过组的方式提取
()表示组 正则支持1-9个组的提取

var html='<div>asd<span>123</span></div>';
// 提取html中的span标签内容
const result=html.match(/<span>(.+?)<\/span>/);
console.info(result[0]); //  <span>123</span>
console.info(result[1]); //  123

提取url信息

const urlReg=/^(https?):\/\/([^\/]+)(\/?[^\?]*)\??([^#]*)#?(.*)$/;
function parseURL(url){
    if(!urlReg.test(url)){
        throw new Error('invalidate url : '+ url);
   }
   const [href, protocol, hostname, pathname, search, hash] = url.match(urlReg);
   return {
       href,
       protocol,
       hostname,
       pathname,
       search,
       hash,
   };
}

测试

parseURL('http://123/123'); 
/*
hash:""
hostname:"123"
href:"http://123/123"
pathname:"/123"
protocol:"http"
search:""
*/
parseURL('http://123/123/123?a=1&b=1#123'); 
/*
hash:"123"
hostname:"123"
href:"http://123/123/123?a=1&b=1#123"
pathname:"/123/123"
protocol:"http"
search:"a=1&b=1"
*/

相关文章

网友评论

    本文标题:JS正则表达式浅析

    本文链接:https://www.haomeiwen.com/subject/cqotdftx.html