A complete collection of regular expressions in js
这次给大家带来js中的正则表达式大全,在js中使用正则表达式的注意事项有哪些,下面就是实战案例,一起来看一下。
1、什么是正则?
正则也叫做规则,让计算机能够读懂人类的规则(正则都是操作字符串的)
2、什么是正则表达式?
正则表达式是由一个字符序列形成的搜索模式。
当你在文本中搜索数据时,你可以用搜索模式来描述你要查询的内容。
正则表达式可以是一个简单的字符,或一个更复杂的模式。
正则表达式可用于所有文本搜索和文本替换的操作。
3、正则的写法
var re = /a/; 正则的简写,其中a是字符串。如果写作 var re = /'a'/;此种写法是错误的
var re = new RegExp('a'); 正则表达式的全写(除了必须要用全写的形式一般建议用简写)注意:当正则需要传参的时候一定要用全称的写法
正则中的常用转义字符
\ s : 空 格 \ S : 非空格
\ d : 数 字 \ D : 非数字
\w : 字 符 \ W : 非字符
//在正则中,数字,字母,下划线统统都是字符
. : 代表任意字符 \ . : 代表真正的点
\ b :独立部分 \ B : 非独立的部分
正则表达式中的量词
{4,7} :最少出现4次,最多出现7次 {4,} :最少出现4次
{4} :正好出现4次 + :至少出现1次,是{1,}的简写
? :0次或1次{0,1} * :至少出现0次{0,}
^ :放正则的最开始位置,就代表起始的位置 $ : 放正则的最后位置,就代表结束的意思
正则中的默认是区分大小写的,如果想要不区分大小写,在正则的最后加标识 i var re = /B/i;
正则默认:正则匹配成功就会结束,不会继续匹配,如果想要全部查找,就要加标识g(全局匹配)。
| :在正则表达式中表示‘或’的意思
正则表达式的字符类:一组相似的字符 [ ]中括号的整体代表一个字符
排除:^ 前面我们已经知道,如果^放在正则的最开始位置,就代表起始的位置,那么如果^放在[ ]里面的话,就代表排除的意思
范围:[a-z] : a~z 的26个字符,整体只代表一位
var str = 'abc'; var re = /a[^bde]c/; alert(re.test(str))//false var str = 'abc'; var re = /a[bde]/; alert(re.test(str));// true \ 数字:重复子项 \ 1:重复的第一个子项 \ 2:重复的第二个子项 [html] view plain copy var str = 'abca'; var re = /(a)(b)(c)\1/; alert(re.test(str));//true [html] view plain copy var str1 = 'c9'; var str2 'cc'; alert(/\w\w/.test(str1));//true alert(/(\w)\1/.test(str2));//true
5、正则表达式的常用方法
test、search、mach、replace
test:正则去匹配字符串,如果匹配成功就返回真,如果匹配失败就返回假
test的写法:正则.text(字符串);
例:
var str1 = 'abcdef'; var re = /b/; alert(re.test(str)); //true
search:正则去匹配字符串,如果匹配成功,就返回匹配成功的位置,如果匹配失败就返回-1
说明
search() 方法不执行全局匹配,它将忽略标志 g。它同时忽略 regexp 的 lastIndex 属性,并且总是从字符串的开始进行检索,这意味着它总是返回 stringObject 的第一个匹配的位置。
search的写法:字符串.search(正则);
例:
var str2 = 'abcde'; var re = /b/; alert(str.search(re)); // 1
match:正则去匹配字符串,如果匹配成功,就返回匹配成功的数组,如果匹配不成功就返回null。
说明:这个方法的行为在很大程度上有赖于 regexp 是否具有标志 g。
match的写法:字符串.match(正则);
例:
var str = ‘haj123sdk443nas33kdjalsd879’; var re = /\d/g; alert(str.match(re)); //[1,2,3,4,4,3,3,3,8,7,9]
例:
var re = /\d\d/g; alert(str.match(re)); // [12,44,33,87];
replace:正则去匹配字符串,匹配成功的字符去替换成新的字符串,replace的第二个参数可以是字符串,也可以是一个回调函数。
replace的写法:字符串.replace(正则,新的字符串); 或者为 :字符串.replace(正则,回调函数);
例:
var str = 'aaa'; var re = /a/; str = str.replace(re,'b'); alert(str); //baa
第一个参数是正则,第二个参数是带$符的字符串
var str3 = '这是一段原始文本,"3c这要替换4d"!'; var newStr = str3.replace( /([0-9])([a-z])/g,"$1" ); console.log( newStr ); //输出: 这是一段原始文本,"3这要替换4"!';
注:此例子为引用点击打开链接
上面的例子是当replace的第二个参数是字符串时,相对来说是比较简单的,那么接下来我们就一起看看当replace的第二个参数是回调函数时的情况。那么在写之前我们先来了解一下正则中的匹配子项
正则中的匹配子项
匹配子项:小括号()。小括号还有另外一个意思,即分组操作
把正则中的整体叫做‘母亲’,然后把左边第一个小括号里面的正则叫第一个子项(母亲的第一个孩子),第二个小括号就是第二个子项,以此类推
注:下面的两个例子为引用点击打开链接
例:1)、回调函数只有一个参数的时候,则函数的参数为匹配的正则的整体
var str4 = '这是一段原始文本,需要替换的内容"aa这要bbb替换ccccc"!'; var newStr = str4.replace( /[a-z]+/g,function ($0){ var str = ''; for (var i = 0; i < $0.length; i++) { str += '*'; }; return str; } ); console.log( newStr ); //这是一段原始文本,需要替换的内容"**这要***替换*****"!
2)、回调函数有多个参数的时候,且看如下例题
var str5 = '这是一段原始文本,需要替换的内容"3c这要替换4d"!'; var newStr = str5.replace( /([0-9])([a-z])/g,function (arg1,arg2,arg3,arg4,arg5){ console.log( arg1 ); console.log( arg2 ); console.log( arg3 ); console.log( arg4 ); console.log( arg5 ); } ); //输出: 3c 3 c 17 这是一段原始文本,需要替换的内容"3c这要替换4d"! 4d 4 d 23 这是一段原始文本,需要替换的内容"3c这要替换4d"!
上面的例子第一个参数arg1表示匹配的整体,arg2表示第一个子表达式,arg3表示第二个子表达式,接下来的参数arg4是一个整数,声明了表示子匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。
以上就是我对正则表达式知识的整理,具体实例也在整理中
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
The above is the detailed content of A complete collection of regular expressions in js. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function