search
HomeWeb Front-endJS TutorialA brief analysis of regular expressions in js

A brief analysis of regular expressions in js

Jun 28, 2017 pm 01:30 PM
javascriptregularexpression

这篇文章主要介绍了深入浅析js中的正则表达式,需要的朋友可以参考下

阅读目录

  • 正则表达式的创建

  • 正则表达式中的特殊字符

  • \ (反斜杠)

  • ^

  • $

  • *,  +,  .(小数点)

  • ? (问号)

  • (x)

  • (?:x)

  • x(?=y), x(?!y), x|y

  • {n}, {n,m}:

  • [xyz], [^xyz]

  • 其他

  • 正则表达式标志

  • 正则表达式使用

很多时候多会被正则表达式搞的晕头转向,最近抽出时间对正则表达式进行了系统的学习,整理如下:

正则表达式的创建

两种方法,一种是直接写,由包含在斜杠之间的模式组成;另一种是调用RegExp对象构造函数

两种方法的创建代码如下:

// 直接创建
const regex1 = /ab+c/;
const regex2 = /^[a-zA-Z]+[0-9]*\W?_$/gi;
// 调用构造函数
const regex3 = new RegExp('ab+c');
const regex4 = new RegExp(/^[a-zA-Z]+[0-9]*\W?_$/, "gi");
const regex5 = new RegExp('^[a-zA-Z]+[0-9]*\W?_$', 'gi');

可以看出,调用RegExp构造函数创建正则表达式时,第一个参数可以是字符串,也可以是直接创建的正则表达式。

需要注意的是:RegExp实例继承的toLocaleString()和toString)()方法都会返回正则表达式的字面量,与创建正则表达式的方式无关

例如:

const ncname = '[a-zA-Z_][\\w\\-\\.]*';
const qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
const startTagOpen = new RegExp(&#39;^<&#39; + qnameCapture);
startTagOpen.toString();    // &#39;/^<((?:[a-zA-Z_][\w\-\.]*\:)?[a-zA-Z_][\w\-\.]*)/&#39;

正则表达式中的特殊字符

\ (反斜杠)

1.在非特殊字符前加反斜杠表示下一个字符是特殊的;

2.将其后的特殊字符转译为字面量;

注意:在使用RegExp构造函数时要将\转译,因为\在字符串里也是转译字符

^

1.匹配输入的开始;

2.在[]中的第一位时表示反向字符集

例子:

/^A/.exec(&#39;an A&#39;)    // null
/^A/.exec(&#39;An E&#39;)    // ["A", index: 0, input: "An E"]

匹配输入的结束

/t$/.exec(&#39;eater&#39;)    // null
/t$/.exec(&#39;eat&#39;)     // ["t", index: 2, input: "eat"]
*, +, .(小数点)

*:匹配前一个表达式0次或多次。等价于 {0,};

+:匹配前面一个表达式1次或者多次。等价于 {1,};

.:

匹配除换行符之外的任何单个字符;

? (问号)

1.匹配前面一个表达式0次或者1次。等价于 {0,1};

2.如果紧跟在任何量词 * + ? {} 的后面,将会使量词变为非贪婪的(匹配尽量少的字符),和缺省使用的贪婪模式正好相反;

3.运用于先行断言

例子:

/\d+/.exec(&#39;123abc&#39;)       // ["123", index: 0, input: "123abc"]
/\d+?/.exec(&#39;123abc&#39;)      // ["1", index: 0, input: "123abc"]

(x)

匹配 'x' 并且记住匹配项,括号表示捕获括号;

例子:

/(foo) (bar) \1 \2/.test(&#39;bar foo bar foo&#39;);  // false
/(bar) (foo) \1 \2/.test(&#39;bar foo bar foo&#39;);  // true
/(bar) (foo) \1 \2/.test(&#39;bar foo&#39;);      // false
/(bar) (foo) \1 \2/.test(&#39;bar foo foo bar&#39;);  // false
/(bar) (foo) \2 \1/.test(&#39;bar foo foo bar&#39;);  // true
&#39;bar foo bar foo&#39;.replace( /(bar) (foo)/, &#39;$2 $1&#39; );  // "foo bar bar foo"

模式 /(foo) (bar) \1 \2/ 中的 '(foo)' 和 '(bar)' 匹配并记住字符串 "foo bar foo bar" 中前两个单词。模式中的 \1 和 \2 匹配字符串的后两个单词。

注意:\1、\2、\n 是用在正则表达式的匹配环节,在正则表达式的替换环节,则要使用像 $1、$2、$n 这样的语法。例如,'bar foo'.replace( /(...) (...)/, '$2 $1' )。

(?:x)

匹配 'x' 但是不记住匹配项,这种叫作非捕获括号;

例子:

&#39;foo&#39;.match(/foo{1,2}/)        // ["foo", index: 0, input: "foo"]
&#39;foo&#39;.match(/(?:foo){1,2}/)      // ["foo", index: 0, input: "foo"]
&#39;foofoo&#39;.match(/(?:foo){1,2}/)     // ["foofoo", index: 0, input: "foofoo"]
&#39;foofoo&#39;.match(/foo{1,2}/)       // ["foo", index: 0, input: "foofoo"]

使用场景:示例表达式 /(?:foo){1,2}/。如果表达式是 /foo{1,2}/,{1,2}将只对 ‘foo' 的最后一个字符 'o‘ 生效。如果使用非捕获括号,则{1,2}会匹配整个 ‘foo' 单词。

x(?=y), x(?!y), x|y

x(?=y):匹配'x'仅仅当'x'后面跟着'y';

x(?!y):匹配'x'仅仅当'x'后面不跟着'y';

x|y: 匹配x或y

这两种匹配的结果都不包含y

例子:

&#39;JackSprat&#39;.match(/Jack(?=Sprat)/)      // ["Jack", index: 0, input: "JackSprat"]
&#39;JackWprat&#39;.match(/Jack(?=Sprat)/)      // null
&#39;JackWprat&#39;.match(/Jack(?=Sprat|Wprat)/)  // ["Jack", index: 0, input: "JackWprat"]
/\d+(?!\.)/.exec("3.141")    // ["141", index: 2, input: "3.141"]

{n}, {n,m}:

{n}:匹配了前面一个字符刚好发生了n次;

{n,m}:匹配前面的字符至少n次,最多m次。如果 n 或者 m 的值是0, 这个值被忽略;

例子:

  /a{2}/.exec(&#39;candy&#39;)     // null
  /a{2}/.exec(&#39;caandy&#39;)    // ["aa", index: 1, input: "caandy"]
  /a{2}/.exec(&#39;caaandy&#39;)    // ["aa", index: 1, input: "caaandy"]
  /a{1,3}/.exec(&#39;candy&#39;)    // ["a", index: 1, input: "candy"]
  /a{1,3}/.exec(&#39;caandy&#39;)   // ["aa", index: 1, input: "caandy"]
  /a{1,3}/.exec(&#39;caaandy&#39;)   // ["aaa", index: 1, input: "caaandy"]
  /a{1,3}/.exec(&#39;caaaandy&#39;)  // ["aaa", index: 1, input: "caaaandy"]

[xyz], [^xyz]

[xyz]:一个字符集合。匹配方括号的中任意字符;

[^xyz]:一个反向字符集。匹配任何没有包含在方括号中的字符;

这两种匹配都可以使用破折号(-)来指定一个字符范围,特殊符号在字符集中没有了特殊意义。

例:

function escapeRegExp(string){
  return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, "\\$&"); 
  //$&表示整个被匹配的字符串
}

例子中的.*+?^=!:${}()都表示字面量,并没有特殊意义。

其他

\b:匹配一个词的边界。一个匹配的词的边界并不包含在匹配的内容中。换句话说,一个匹配的词的边界的内容的长度是0;

\B: 匹配一个非单词边界;

例子:

  /\bm/.exec(&#39;moon&#39;)             // ["m", index: 0, input: "moon"]
  /\bm/.exec(&#39;san moon&#39;)           // ["m", index: 4, input: "san moon"]
  /oo\b/.exec(&#39;moon&#39;)             // null
  /\B../.exec(&#39;noonday&#39;)          // ["oo", index: 1, input: "noonday"]
  /y\B../.exec(&#39;possibly yesterday&#39;)    // /y\B../.exec(&#39;possibly yesterday&#39;)

\d:匹配一个数字,等价于[0-9];

\D:匹配一个非数字字符,等价于[^0-9];

\f:匹配一个换页符 (U+000C);

\n:匹配一个换行符 (U+000A);

\r:匹配一个回车符 (U+000D);

\s:匹配一个空白字符,包括空格、制表符、换页符和换行符,等价于[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff];

\S:匹配一个非空白字符,等价于[^ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff];

\w:匹配一个单字字符(字母、数字或者下划线),等价于[A-Za-z0-9_];

\W:匹配一个非单字字符,等价于[^A-Za-z0-9_];

正则表达式标志

g:全局搜索;

i:不区分大小写;

m:多行搜索;

正则表达式使用

RegExp有exec()和test()方法;

exec匹配的结果为:匹配结果、捕获结果,index和input。

test匹配的结果为true或false,效率比exec要高。

String有match(),replace(),search(),split()方法;

match匹配的结果同RegExp的exec,replace根据正则表达式替换,search查找所以位置,split根据正则表达式分割字符串。

其中,当replace有function时,参数说明如下:

* 匹配项
* 记忆项(括号里面的项)
* ...
* 匹配的index
* input输入项

The above is the detailed content of A brief analysis of regular expressions in js. For more information, please follow other related articles on the PHP Chinese website!

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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)