/\w+[\w\.]*@[\w\.]+\.\w+/
const regex = /\w+[\w\.]*@[\w\.]+\.\w+/ regex.test('666@email.com') // true regex.test('july@e.c') // true regex.test('_@email.com.cn') // true regex.test('july_1234@email.com') // true regex.test('@email.com') // false regex.test('julyemail.com') // false regex.test('july.email.com') // false regex.test('july@') // false regex.test('july@email') // false regex.test('july@email.') // false regex.test('july@.') // false regex.test('july@.com') // false regex.test('-~!#$%@email.com') // false
/https?:\/\/(\w*:\w*@)?[-\w\.]+(:\d+)?(\/([\w\/\.]*(\?\S+)?)?)?/
const regex = /https?:\/\/(\w*:\w*@)?[-\w\.]+(:\d+)?(\/([\w\/\.]*(\?\S+)?)?)?/ regex.test('http://www.forta.com/blog') // true regex.test('https://www.forta.com:80/blog/index.cfm') // true regex.test('https://www.forta.com') // true regex.test('http://ben:password@www.forta.com/') // true regex.test('http://localhost/index.php?ab=1&c=2') // true regex.test('http://localhost:8500/') // true
我在本地随便写了一个html文件,包含css、html和js3个部分,是一个完整的网页。javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> /* 这是css的多行注释 这是css的多行注释 这是css的多行注释 */ * { margin: 0; padding: 0; /* 这是css的多行注释 */ } html { color: #000; } </style> </head> <body> <h1>h1 title</h1> <!-- 这是html注释 --> <h2>h2 title</h2> <!-- 这是html注释 --> <button style="/* 这是行内css的注释 */color: red/* 这是行内css的注释 */">click me</button> <button onclick="/* 这是行内js的注释 */alert('july')/* 这是行内js的注释 */">click me 2</button> <!-- 这是html注释 --> <button onclick="// 这是行内js的注释 alert(/* 注释 */'july') //这是行内js的注释 'sdfs' " style='color: blue'>click me 3</button> <!-- 这是html注释 --> <script> // 这是js单行注释 // 这是js单行注释 这是js单行注释 function func() { console.log('test'); // 这是js单行注释 } /* * 这是js多行注释 * 这是js多行注释 这是js多行注释 */ function func2() { // 这是js单行注释 /* 这是js多行注释 */ console.log('test'); /* 这是js多行注释 */ } </script> </body> </html>
const htmlStr = `html字符串`; // 将上面的html内容拷贝于此,因为太长,就再也不拷贝 // 匹配 /* */ htmlStr.match(/\/\*[^]*?\*\//g); // 该行代码会返回一个数组,长度为10,数组的每一个元素分别对应匹配到的 /* */,因为篇幅有限,就不将结果展现到这里了 // 匹配 <!-- --> htmlStr.match(/<!--[^]*?-->/g); // 匹配 // htmlStr.match(/(\/\/.*?(?=(["']\s*\w+\s*=)|(["']\s*>)))|(\/\/.*)/g);
<button onclick=" alert('july') //这是行内js的注释 'sdfs' " style='color: blue'>click me 3</button> <button onclick=" alert('july') //这是行内js的注释 'sdfs' ">click me 3</button>
咱们经过图片详细解析一下php
为了方便,最终代码选择在node环境中执行,由于最初的需求是将html中的全部注释去掉,因此咱们使用了字符串的replace方法,该方法接收两个参数,第一个参数是正则表达式,第二个参数是须要替换成的内容。css
const fs = require('fs'); // regex.html 是放在同级目录下的html源文件 fs.readFile('./regex.html', 'utf8', (err, data) => { if (err) throw err; console.log( data .replace(/\/\*[^]*?\*\//g, '') // 替换 /* */ .replace(/<!--[^]*?-->/g, '') // 替换 <!-- --> .replace(/(\/\/.*?(?=(["']\s*\w+\s*=)|(["']\s*>)))|(\/\/.*)/g, '') // 替换 // ); });