How to implement regular grouping and lookahead matching in JS
这次给大家带来如何实现JS内正则分组与前瞻匹配,实现JS内正则分组与前瞻匹配的注意事项有哪些,下面就是实战案例,一起来看一下。
1.分组匹配:
1.1捕获性分组匹配 ()
2.2非捕获性分组匹配 (?:)
2前瞻匹配:
2.1正向前瞻匹配: (?=表达式) 后面一定要匹配有什么
2.2反向前瞻匹配: (?!表达式) 后面一定不能要有什么
1.1、捕获性分组匹配 ()
var str1 = "holle word 123456 can 12s a 123 a"; var reg1 =/([a-z]+)\s(\d+)/; //不是全局模式 ,以() 分组,这里有两组,每一组都将匹配得到 var regg1 = /([a-z]+)\s(\d+)/g; //全局模式 g,以() 分组,这里有两组,每一组都将匹配得到 //res :非全局模式 console.log(reg1.exec(str1)); //exec()方法:["wold 123456","word","123456"] console.log(str1.match(reg1));//match()方法:["word 123456","word","123456"] console.log(RegExp.$1);//获取到第一个分组 ([a-z]+) 匹配的结果 :word console.log(RegExp.$2);//获取到第一个分组 (\d+) 匹配的结果 :123456 //res :全局模式 console.log(regg1.exec(str1)); //exec()方法:["wold 123456","word","123456"] console.log(str1.match(regg1));//match()方法:["word 123456","can 12","a 123"] console.log(RegExp.$1);//获取到第一个分组 ([a-z]+) 匹配的结果 :a console.log(RegExp.$2);//获取到第一个分组 (\d+) 匹配的结果 :123
分析:这个正则表达式匹配的是,至少一个字母,跟着一个空格,然后至少一个数字,
非全局就是第一次匹配正确就不会再往后匹配 了,
1.exec()方法提取的值是规定的,第一个值是正则表达式相匹配的文本,如上示例的"/([a-z]+)\s(\d+)/",第2个值是第一个字子表达式(即第一个分组),如上示例的"([a-z])",以此类推
2.即使是全局模式,exec()都不会全局匹配,循环调用exec()是唯一全局匹配的方式,所以你会发现上面使用exec()方法的结果是一样
3.而 match 方法在全局模式的捕获性分组匹配,会对正则表达式全局匹配,但是不会对子表达式匹配(分组),所以你会发现上面str1.match(regg1) 的结果是不会单独以分组([a-z]+)字母或者分组(\d+)数字出现,而是全局匹配整一个正则,所以结果是["word 123456","can 12","a 123"]
4.match 方法在非全局模式 的捕获性分组匹配中,会对正则表达式全局匹配,也会对子表达式匹配(分组),所以你发现,str1.match(reg1)匹配的结果有单独分组的匹配,但是因为是非全局,所以第一次匹配正确就结束了,只有["wold 123456","word","123456"],“wold 123456” 是整个表达式匹配的结果,“word” 是第一个分组([a-z]+)匹配的结果,“123456” 是第二分组(\d+) 匹配的结果
5.$1,$2... 分别包含正则表达式中的相对应反向引用,在全局与非全局模式,如果结果集有多个,会以最后一次匹配的结果来算,如上面,全局模式,匹配一共有三个符合的,["word 123456","can 12","a 123"],那么就以最后一个"a 123"为所有分组得到的结果,第一个分组是([a-z]+) 匹配的是字母所以是a,第二个分组是数字(\d+),所以是123 ,以此类推,如果只出现一次,一次也是当最后一次,自然也是一样的分析,哈哈哈,有点多余。。。。
1.2 (?:) 非捕获性分组匹配 ,不捕获子表达式(分组)
var str1 = "holle word 123456 can 12s a 123 a"; var reg2 = /(?:[a-z]+)\s(?:\d+)/; var regg2 = /(?:[a-z]+)\s(?:\d+)/g; //res :非全局模式 console.log(reg2.exec(str1));// exec(): 直接匹配["wold 123456"], console.log(str1.match(reg2));//match()方法:["word 123456"] //res :全局模式 console.log(regg2.exec(str1));// exec(): 直接匹配["wold 123456"], console.log(str1.match(regg2));//match()方法:["word 123456","can 12","a 123"]
分析,和上面的捕获性分组匹配是一样的解析,只是不再匹配子表达式(分组)
2.1正向前瞻匹配: (?=表达式) 后面一定要匹配有什么
注意:前瞻分组匹配(?=表达式) 会作为匹配内容,不会作为匹配结果返回
//实例,提取以jpg类型的图片名称 var str2 = "ab.jpg,admin/12.gif,and.jpg"; var reg3 = /[^\\]\w+(?=\.jpg)/g; console.log(str2.match(reg3));//["ab", ",and"]
2.2反向前瞻匹配: (?!表达式) 后面一定不能要有什么
//示例:匹配 连续a字母三个以上,且后面不能有数字 var str3 = "aaa12345,aaaadmin,aaaaaadd,dlala"; var reg4 = /a{3,}(?!\d+)/g; console.log(str3.match(reg4));//["aaaa","aaaaaa"]
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
怎么使用webpack3.0配置webpack-dev-server
The above is the detailed content of How to implement regular grouping and lookahead matching in JS. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft