8

前端常用正则表达式

 2 years ago
source link: https://segmentfault.com/a/1190000041036687
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

整理了前端常用的正则表达式,包括链接,html标签,邮箱,手机号等常用的正则表达式,提前完成任务下班。

本文首发于 前端常用正则表达式,转载请注明来源

匹配手机号正则

/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/gm
(555)-555-5555
555-555-5555
+1-555-532-3455
13700000000
test 34  // 不匹配
130 // 不匹配

匹配html标签

/<\s*a[^>]*>(.*?)<\s*/\s*a>/g

测试匹配a标签的数据,如果要匹配其他标签手动修改上述正则即可

// 输入
你好 <a href="//interview.kelen.cc">https://interview.kelen.cc</a> 请说 <a href="/work">Work</a> 卧槽 <a href="/about">about</a> 拜拜。

// 输出
<a href="//interview.kelen.cc">https://interview.kelen.cc</a>
<a href="/work">Work</a>
<a href="/about">about</a>

判断是否是有效的IP地址

/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/gm
// 输入
000.0000.00.00
192.168.1.1
912.456.123.123

// 输出
192.168.1.1

判断邮箱地址

/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/igm

匹配括号的内容

/\(([^)]+)\)/g
"cc (de) asd (adsad) akl; (https://www.interview.kelen.cc)".match(/\(([^)]+)\)/g)
输出:['(de)', '(adsad)', '(https://www.interview.kelen.cc)']

/\(([^)]+)\)/g.exec("cc (de) asd (adsad) akl; (https://www.interview.kelen.cc)")
输出:['(de)', 'de', index: 3, input: 'cc (de) asd (adsad) akl; (https://www.interview.kelen.cc)', groups: undefined]

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK