[regex] 更多的正则表达式使用例子
#匹配URL
//不考虑注入 var a = /^(?:([A-Za-z]+):)?(\/{0,2})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/; var b = 'http://www.ok.com:80/goodbye?q#fragment'; var c = a.exec(b); console.log(c); var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash']; var blanks = ' '; var i; for (i = 0; i < names.length; i += 1) { console.log(names[i] + ':' + blanks + c[i]); } //url: http://www.ok.com:80/goodbye?q#fragment //scheme: http //slash: // //host: www.ok.com //port: 80 //path: goodbye //query: q //hash: fragment
#
//匹配数字 var parse_number = /^-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?$/i; var test = function(num) { console.log(parse_number.test(num)); }; test('1'); // true test('number'); // false test('98.6'); // true test('132.21.86.100'); // false test('123.45E-67'); // true test('123.45D-67'); // false
#转换成整数
filterInt = function (value) { if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) return Number(value); return NaN; }
//寻找重复的单词 var doubled_words = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1/gi; //匹配非ASCII特殊字符的字符 /[^!-\/:-@\[-`{-˜]/ //匹配成对的引号 /(['"])[^'"]*\1/ //将英文引号转换为中文引号,且不改变引号里的内容 var quote = /"([^"]*)"/g; str.replace(quote,'“$1”'); //也是匹配URL /(\w+):\/\/([\w.]+)\/(\S*)/; //split 以,分割,允许有空格 "1, 2, 3, 4, 5".split(/\s*,\s*/);
#
所有空格符 /\s+/g 所有非空格符 /[^\s]+/g 所有数字 /\d+/g 所有非数字 /[^\d]+/g 匹配首尾的 - /^-|-$/g 匹配左右两侧空白符 /^\s+|\s+$/g 匹配这几个单词 /\bsome|foo|the|by|for|poor\b/ig 匹配非字母和数字 /[^a-z0-9]+/ig 匹配第一个‘bat’或‘cat’ /[bc]at/ 匹配 000-00-0000 /\d{3}-\d{2}-\d{4}/
#
//字符转换 function DNAStrand(dna) { var pairs = { A: 'T', T: 'A', C: 'G', G: 'C', } return dna.replace(/./g, function(c) { return pairs[c] }) } //检测成对的括号 function isBalanced(s) { s = s.replace(/[^()]+/g, ''); var m = /\(\)/, r = /\(\)/g; while (m.test(s)) { s = s.replace(r, ''); } return s === ''; }
#密码匹配
//密码匹配,至少有一个大写字母,小写字母,数字,字符串大于6位 function validate(password) { return /^[A-Za-z0-9]{6,}$/.test(password) && /[A-Z]+/.test(password) && /[a-z]+/.test(password) && /[0-9]+/.test(password); } function validate(password) { return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/.test(password); } console.log(validate('djI38D55')); console.log(validate('a2.d412')); console.log(validate('JHD5FJ53')); console.log(validate('123')); console.log(validate('!123'));
#
//匹配重复字母 function duplicateCount(text) { return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length; } function duplicateCount(text) { return (text.toLowerCase().match(/(.)(?=.*\1)/g) || []).filter(function(c, i, letters) { return letters.indexOf(c) === i }).length }
#
//求数字的底数和指数 var isPP = function(n) { var temp = 0; if (/^(\d+\.+\d+|[0-3])$/.test('' + n)) { return null; } for (var i = 2; i < n; i++) { if (Math.pow(i, 2) > n) { return null; } for (var j = 2; j < n; j++) { temp = Math.pow(i, j); if (temp > n) { break; } if (temp === n) { return [i, j]; } } } } console.log(isPP(100)); console.log(isPP(32)); console.log(isPP(27)); console.log(isPP(8)); console.log(isPP(9)); console.log(isPP(5)); console.log(isPP(4)); console.log(isPP(4.1)); console.log(isPP(1)); console.log(isPP(2)); console.log(isPP(3)); console.log(isPP(0));
#简单的字母匹配查字典
function autocomplete(input, dictionary) { var a = input.toLowerCase().replace(/[^a-z]/g, ''); var b = []; var reg = new RegExp('^'+a+'.*$'); for (var i = 0; i < dictionary.length; i++) { if (dictionary[i].toLowerCase().search(reg) > -1) { b.push(dictionary[i]); } if (b.length == 5) { return b; } } return b; } function autocomplete(input, dictionary){ var r = new RegExp('^' + input.replace(/[^a-z]/gi,''), 'i'); return dictionary.filter(function(w){ return r.test(w); }).slice(0, 5); } console.log(autocomplete('ai', ['airplane', 'airport', 'apple', 'ball']));
#
function dirReduc(arr) { var reg = /NORTHSOUTH|SOUTHNORTH|EASTWEST|WESTEAST/, a = arr.join(''); while (reg.test(a)) { a = a.replace(reg, ''); } return a.match(/NORTH|SOUTH|EAST|WEST/g) || []; } dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"])//["WEST"] dirReduc(["NORTH", "WEST", "SOUTH", "EAST"])// ["NORTH", "WEST", "SOUTH", "EAST"] dirReduc(["NORTH", "SOUTH", "EAST", "WEST", "EAST", "WEST"])//[]
#
var Mod4 = /^([^\d]*\[(\+|-)*(?:0)*\d+\][^\d]*)+$/; var Mod4 = /\[[-+]?(?:[048]|\d*[02468][048]|\d*[13579][26])]/; var Mod4 = /\[[-+]?([048]|\d*([02468]+[048]|[13579][26]))\]/;
Mod4.test(str)
"[+05620]" // 5620 is divisible by 4 (valid) "[+05621]" // 5621 is not divisible by 4 (invalid) "[-55622]" // -55622 is not divisible by 4 (invalid) "[005623]" // 5623 invalid "[005624]" // 5624 valid "[-05628]" // valid "[005632]" // valid "[555636]" // valid "[+05640]" // valid "[005600]" // valid "the beginning [0] ... [invalid] numb[3]rs ... the end" // 0 is valid "No, [2014] isn't a multiple of 4..." // 2014 is invalid "...may be [+002016] will be." // 2016 is valid // invalid "[+05621]", "[-55622]", "[005623]", "[~24]", "[8.04]", "No, [2014] isn't a multiple of 4..."
#文件路径简单处理
function imageFile(url, wid, hei) { var width = wid || 100; var height = hei || 100; return (url + '').replace(/(\w+)\.(\w+)$/g, '$1' + '_' + width + '_' + height + '.$2'); }
#格式化数字
var a = 9999999999; var b = (a + '').replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,'); console.log(b); //99,999,999,999
#转化驼峰法
var foo="get-element-by-id"; var b = foo.replace(/-([a-z])/g,up); function up(match,p1){ return p1.toUpperCase(); }
#类似模板替换
function fn(str) { this.str = str; } fn.prototype.format = function() { var args = [].slice.call(arguments); var i = 0; return this.str.replace(/\{\d+\}/g, function(a) { return args[i++] || ""; }); } var t = new fn('<p><a href="{0}">{1}</a><span>{2}</span></p>'); console.log(t.format('http://www.alibaba.com', 'Alibaba', 'Welcome'));
#