search
HomeWeb Front-endHTML Tutorial20 regular expressions that will save you 1,000 lines of code

正则表达式,一个十分古老而又强大的文本处理工具,仅仅用一段非常简短的表达式语句,便能够快速实现一个非常复杂的业务逻辑。熟练地掌握正则表达式的话,能够使你的开发效率得到极大的提升。

正则表达式经常被用于字段或任意字符串的校验,如下面这段校验基本日期格式的JavaScript代码:

<span class="hljs-keyword">var reg = <span class="hljs-regexp">/^(\\d{1,4})(-|\\/)(\\d{<span class="hljs-number">1,<span class="hljs-number">2})\\<span class="hljs-number">2(\\d{<span class="hljs-number">1,<span class="hljs-number">2})$/; 
<span class="hljs-keyword">var r = fieldValue.match(reg);             
<span class="hljs-keyword">if(r==<span class="hljs-literal">null)alert(<span class="hljs-string">'Date format error!');</span></span></span></span></span></span></span></span></span></span></span>

下面是技匠整理的,在前端开发中经常使用到的20个正则表达式。

1 . 校验密码强度

密码的强度必须是包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间。

^(?=.<span class="hljs-emphasis">*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$</span>

2. 校验中文

字符串仅能是中文。

^[\\u4e00-\\u9fa5]{0,}$

3. 由数字、26个英文字母或下划线组成的字符串

^\\w+$

4. 校验E-Mail 地址

同密码一样,下面是E-mail地址合规性的正则检查语句。

[<span class="hljs-string">\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[<span class="hljs-string">\\w!#$%&'*+/=?^_`{|}~-]+)<span class="hljs-emphasis">*@(?:[\\w](?:[\\w-]*[<span class="hljs-string">\\w])?\\.)+[<span class="hljs-string">\\w](<span class="hljs-link">?:[\\w-]*[\\w])?</span></span></span></span></span></span>

5. 校验身份证号码

下面是身份证号码的正则校验。15 或 18位。

15位:

^[<span class="hljs-number">1-<span class="hljs-number">9]\\d{<span class="hljs-number">7}((<span class="hljs-number">0\\d)<span class="hljs-params">|(1[0-2]))(([0|<span class="hljs-number">1<span class="hljs-params">|2]\\d)|<span class="hljs-number">3[<span class="hljs-number">0-<span class="hljs-number">1])\\d{<span class="hljs-number">3}$</span></span></span></span></span></span></span></span></span></span></span>

18位:

^[<span class="hljs-number">1-<span class="hljs-number">9]\\d{<span class="hljs-number">5}[<span class="hljs-number">1-<span class="hljs-number">9]\\d{<span class="hljs-number">3}((<span class="hljs-number">0\\d)<span class="hljs-params">|(1[0-2]))(([0|<span class="hljs-number">1<span class="hljs-params">|2]\\d)|<span class="hljs-number">3[<span class="hljs-number">0-<span class="hljs-number">1])\\d{<span class="hljs-number">3}([<span class="hljs-number">0-<span class="hljs-number">9]<span class="hljs-params">|X)$</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

6. 校验日期

“yyyy-mm-dd“ 格式的日期校验,已考虑平闰年。

^(?:(?!0000)[<span class="hljs-string">0-9]{4}-(?:(?:0[<span class="hljs-string">1-9]|1[<span class="hljs-string">0-2])-(?:0[<span class="hljs-string">1-9]|1[<span class="hljs-string">0-9]|2[<span class="hljs-string">0-8])|(?:0[<span class="hljs-string">13-9]|1[<span class="hljs-string">0-2])-(?:29|30)|(?:0[<span class="hljs-string">13578]|1[<span class="hljs-string">02])-31)|(?:[<span class="hljs-string">0-9]{2}(?:0[<span class="hljs-string">48]|[<span class="hljs-string">2468][<span class="hljs-symbol">048]|[<span class="hljs-string">13579][<span class="hljs-symbol">26])|(?:0[<span class="hljs-string">48]|[<span class="hljs-string">2468][<span class="hljs-symbol">048]|[<span class="hljs-string">13579][<span class="hljs-symbol">26])00)-02-29)$</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

7. 校验金额

金额校验,精确到2位小数。

^[0-9]+(.[0-9]{2})?$

8. 校验手机号

下面是国内 13、15、18开头的手机号正则表达式。(可根据目前国内收集号扩展前两位开头号码)

^(<span class="hljs-number">13[<span class="hljs-number">0-<span class="hljs-number">9]<span class="hljs-params">|14[5|<span class="hljs-number">7]<span class="hljs-params">|15[0|<span class="hljs-number">1<span class="hljs-params">|2|<span class="hljs-number">3<span class="hljs-params">|5|<span class="hljs-number">6<span class="hljs-params">|7|<span class="hljs-number">8<span class="hljs-params">|9]|<span class="hljs-number">18[<span class="hljs-number">0<span class="hljs-params">|1|<span class="hljs-number">2<span class="hljs-params">|3|<span class="hljs-number">5<span class="hljs-params">|6|<span class="hljs-number">7<span class="hljs-params">|8|<span class="hljs-number">9])\\d{<span class="hljs-number">8}$</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

9. 判断IE的版本

IE目前还没被完全取代,很多页面还是需要做版本兼容,下面是IE版本检查的表达式。

^.<span class="hljs-emphasis">*MSIE [5-8](?:\\.[0-9]+)?(?!.*Trident\\/[5-9]\\.0).*$</span>

10. 校验IP-v4地址

IP4 正则语句。

\\b(?:(?:25[<span class="hljs-string">0-5]|2[<span class="hljs-string">0-4][<span class="hljs-symbol">0-9]|[<span class="hljs-string">01]?[<span class="hljs-string">0-9][<span class="hljs-symbol">0-9]?)\\.){3}(?:25[<span class="hljs-string">0-5]|2[<span class="hljs-string">0-4][<span class="hljs-symbol">0-9]|[<span class="hljs-string">01]?[<span class="hljs-string">0-9][<span class="hljs-symbol">0-9]?)\\b</span></span></span></span></span></span></span></span></span></span></span></span>

11. 校验IP-v6地址

IP6 正则语句。

(([0-9a<span class="hljs-_">-fA-F]{1,4}:){7,7}[0-9a<span class="hljs-_">-fA-F]{1,4}|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,7}:|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,6}:[0-9a<span class="hljs-_">-fA-F]{1,4}|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,5}(:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,2}|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,4}(:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,3}|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,3}(:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,4}|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,2}(:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,5}|[0-9a<span class="hljs-_">-fA-F]{1,4}:((:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,6})|:((:[0-9a<span class="hljs-_">-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a<span class="hljs-_">-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a<span class="hljs-_">-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>

12. 检查URL的前缀

应用开发中很多时候需要区分请求是HTTPS还是HTTP,通过下面的表达式可以取出一个url的前缀然后再逻辑判断。

<span class="hljs-keyword">if (!s.match(<span class="hljs-regexp">/^[a-zA-Z]+:\\/\\<span class="hljs-comment">//))
{
    s = <span class="hljs-string">'http://' + s;
}</span></span></span></span>

13. 提取URL链接

下面的这个表达式可以筛选出一段文本中的URL。

^(f|ht){<span class="hljs-number">1}(tp|tps):\\<span class="hljs-regexp">/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- ./?%&=]*)?</span></span>

14. 文件路径及扩展名校验

验证windows下文件路径和扩展名(下面的例子中为.txt文件)

^([a-zA-Z]\\<span class="hljs-symbol">:|\\\\)\\\\([^\\\\]+\\\\)*[^\\/<span class="hljs-symbol">:*?<span class="hljs-string">"<>|]+\\.txt(l)?$</span></span></span>

15. 提取Color Hex Codes

有时需要抽取网页中的颜色代码,可以使用下面的表达式。

^<span class="hljs-comment">#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$</span>

16. 提取网页图片

假若你想提取网页中所有图片信息,可以利用下面的表达式。

\\<span class="xml"><span class="hljs-tag">< *[<span class="hljs-attr">img][^\\\\>]<span class="hljs-emphasis">*[src] *= <span class="hljs-emphasis">*[\\"\\']{0,1}([^\\"\\'\\ >]*)</span></span></span></span></span>

17. 提取页面超链接

提取html中的超链接。

(<a\\<span class="hljs-keyword">s*(?!.*\\brel=)[^>]*)(href=<span class="hljs-string">"https?:\\/\\/)((?!(?:(?:www\\.)?'.implode('|(?:www\\.)?', $follow_list).'))[^"]+)<span class="hljs-string">"((?!.*\\brel=)[^>]*)(?:[^>]*)></span></span></span>

18. 查找CSS属性

通过下面的表达式,可以搜索到相匹配的CSS属性。

^\\s*[a-zA-Z\\-]+\\s*[:]{<span class="hljs-number">1}\\s[a-zA-Z0<span class="hljs-number">-9\\s.<span class="hljs-comment">#]+[;]{1}</span></span></span>

19. 抽取注释

如果你需要移除HMTL中的注释,可以使用如下的表达式。

<span class="hljs-comment"><!--(.*?)--></span>

20. 匹配HTML标签

通过下面的表达式可以匹配出HTML中的标签属性。

<\\/?\\w+((\\s+\\w+(\\s*=\\s*(?<span class="hljs-symbol">:<span class="hljs-string">".*?"|<span class="hljs-string">'.*?'|[\\^<span class="hljs-string">'">\\s]+))?)+\\s*|\\s*)\\/?></span></span></span></span>

正则表达式的相关语法

下面是我找到的一张非常不错的正则表达式 Cheat Sheet,可以用来快速查找相关语法。

学习正则表达式

我在网上看到了一篇相当不错的正则表达式快速学习指南,有兴趣继续深入学习的同学可以参考。

正则表达式在线测试工具

regex101是一个非常不错的正则表达式在线测试工具,你可以直接在线测试你的正则表达式哦。

 
 
阅读正文请点击此处
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages?How to efficiently add stroke effects to PNG images on web pages?Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element?What is the purpose of the <datalist> element?Mar 21, 2025 pm 12:33 PM

The article discusses the HTML <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element?What is the purpose of the <progress> element?Mar 21, 2025 pm 12:34 PM

The article discusses the HTML <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element?What is the purpose of the <meter> element?Mar 21, 2025 pm 12:35 PM

The article discusses the HTML <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment