目录
问题
- 最近在js中使用正则时,出现了相同的字符串,给相同的正则进行匹配,结果非常规律地返回一次true,一次false,一次true,一次false的结果
- 一开始感觉非常不可思议,因为正则表达式和字符串都一样,进行匹配却得到了不同的结果,而且还固定交替出现true和false。
- 后来直接百度搜"JS正则表达式离奇bug",结果出现了很多关于全局匹配/g的解答,这也正是我遇到的问题的根源所在。
- 下面我们详细聊聊。
全局匹配/g
- 首先我们需要知道正则表达式的匹配方式,总的来说无非两种:
- 搜索:只要求给定字符串中存在可以被正则表达式匹配的字符(或字符串)即算成功
- 例如:
- 给定字符串:"123abc456"
- 正则表达式:/\d+/
- 结果:true
- "123"
- "456"
- 可以看到,整个字符串并不能匹配正则表达式,但它存在可以匹配的子串"123"和"456",因此匹配成功,或者说是搜索成功
- 例如:
- 完全匹配:即给定的字符串必须可以被正则表达式完全匹配才算成功
- 例如:
- 给定字符串:"123abc456"
- 正则表达式:/^\d+$/
- 注意表达式的开头多了个^(即从字符串开头)和末尾的$(到字符串的结尾),表示整个字符串得从头到尾正确匹配我们的正则表达式
- 结果:false
- 由于字符串不能匹配正则表达式,因此匹配失败
- 例如:
- 搜索:只要求给定字符串中存在可以被正则表达式匹配的字符(或字符串)即算成功
- 而本文的问题就出现在搜索模式上
- 全局匹配。在声明正则表达式之后加上g,如:
- /\d+/g 或 new RegExp("\\d+", "g")
- 注意全局匹配是搜索的方式
- 之前就是理解错了全局匹配的意思,以为它是完全匹配,所以用错了
分析
- 使用全局匹配时,正则表达式对象的 lastIndex 属性需要注意:
- 初始化默认为0
- 若匹配成功,则lastIndex被置为被匹配的子字符串的末尾下标再+1
- 若匹配失败,则lastIndex被置为0
- 每次使用该正则表达式对象去匹配时,都会从这个lastIndex开始
- 因此,在文章开头,我们使用同一个全局匹配模式的正则对象去匹配时,过程如下:
- 假设字符串为"123456"
- 假设正则表达式为:/\d+/g
- 第一次使用,lastIndex初始为0,字符串整个被匹配,lastIndex = 6(被匹配字符串的末尾(字符6)的下标5 + 1),匹配成功
- 第二次使用,从lastIndex=6开始拿字符串,正则对象拿到的待匹配字符串其实就是空串 "",显然空串不能匹配我们的正则,因此匹配失败,注意此时lastIndex因匹配失败被置为0
- 第三次使用,从lastIndex=0开始,又和第一次使用一样,匹配成功且lastIndex = 6
- 第四次使用,从lastIndex=6开始,和第二次使用一样,拿到了空串,匹配失败且lastIndex = 0
- 因此会出现交替的成功、失败
解决
- 知道了原因后其实就解决就简单了,这里主要由四种办法:
- 1:简单粗暴把正则表达式的全局匹配/g去掉,使用完全匹配,即创建正则对象时不使用/g参数
- 2:每次使用前,把正则对象的 lastIndex 手动置0
- 3:每次都重新创建正则对象,因为初始化默认的lastIndex为0,本质和第二种办法差不多
- 4:奇特的方法,既然是本应匹配成功的时候却交替的出现成功和失败,而本应匹配失败的时候是一直出现失败。那么我们就可以连续两次进行匹配,将两次的结果或 | 起来就可以了。
- 如:字符串str = "123456" 和正则表达式 reg = /\d+/g
- return (reg.test(str) | reg.test(str));
- 但最好还是直接用第一种,明确你使用正则的目的
When Taylor Swift https://shake-it-off.taylor-swift-ar.com released “Shake It Off” in 2014, she had no idea how much the song would impact her life and music career.
Priyanka Chopra https://baywatch.priyankachopra-ar.com is an Indian actress, singer, film producer and model who has achieved global success.
Liverpool https://england.liverpool-ar.com holds a special place in the history of football in England.
Автомобили Hongqi https://hongqi-krasnoyarsk.ru в наличии – официальный дилер Hongqi Красноярск
https://amoxildelivery.pro/# amoxicillin 500mg no prescription
how to buy generic clomid: get cheap clomid without insurance – where can i get cheap clomid without dr prescription
Juventus Football Club https://italy.juventus-ar.com is one of the most successful and decorated clubs in the history of Italian and world football.
Chelsea https://england.chelsea-ar.com is one of the most successful English football clubs of our time.
The history of one of France’s https://france.paris-saint-germain-ar.com most famous football clubs, Paris Saint-Germain, began in 1970, when capitalist businessmen Henri Delaunay and Jean-Auguste Delbave founded the club in the Paris Saint-Germain-en-Laye area.
Zinedine Zidane https://real-madrid.zinedine-zidane-ar.com the legendary French footballer, entered the annals of football history as a player and coach.
Travis Scott https://astroworld.travis-scott-ar.com is one of the brightest stars in the modern hip-hop industry.
Howdy! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really enjoy your content. Please let me know. Thank you
can i purchase cheap clomid without a prescription: cost generic clomid without insurance – where buy clomid
http://ciprodelivery.pro/# ciprofloxacin generic price
https://paxloviddelivery.pro/# paxlovid covid
Paxlovid over the counter: paxlovid buy – Paxlovid buy online
cheap clomid without insurance: order generic clomid tablets – cheap clomid without a prescription
http://ciprodelivery.pro/# buy ciprofloxacin over the counter
canadian pharmacy antibiotics: best mail order pharmacy canada – ed drugs online from canada
mexico pharmacy: buying from online mexican pharmacy – mexican online pharmacies prescription drugs
canadian online pharmacy reviews: canadian pharmacies compare – canadian pharmacy meds review
best online pharmacies in mexico: mexican rx online – mexican drugstore online
https://indiapharmast.com/# best india pharmacy
best india pharmacy: reputable indian online pharmacy – indian pharmacy
п»їlegitimate online pharmacies india: indian pharmacies safe – Online medicine order
canadapharmacyonline com: canada drugs online reviews – safe canadian pharmacies
pharmacies in mexico that ship to usa mexican mail order pharmacies pharmacies in mexico that ship to usa
магазин аккаунтов роблокс магазин аккаунтов роблокс .
http://indiapharmast.com/# indian pharmacy paypal
canada pharmacy world: vipps canadian pharmacy – canadian pharmacy phone number
фоновое озвучивание помещений фоновое озвучивание помещений .
canadian pharmacy world canada pharmacy online canada pharmacy 24h
top 10 online pharmacy in india: indianpharmacy com – reputable indian pharmacies
buying from online mexican pharmacy: mexico drug stores pharmacies – buying prescription drugs in mexico
canadianpharmacymeds com: best online canadian pharmacy – reputable canadian pharmacy
https://indiapharmast.com/# indian pharmacy
precription drugs from canada best canadian online pharmacy canadian pharmacy tampa
canada pharmacy 24h: cross border pharmacy canada – reddit canadian pharmacy
top online pharmacy india: cheapest online pharmacy india – online shopping pharmacy india
best online canadian pharmacy canadian discount pharmacy pet meds without vet prescription canada
mail order pharmacy india: indian pharmacy – top online pharmacy india
https://canadapharmast.com/# canada drug pharmacy
buy prescription drugs from india: indianpharmacy com – india pharmacy
Jackie Chan https://karate-kid.jackiechan-ar.com was born in 1954 in Hong Kong under the name Chan Kong San.
online pharmacy india: cheapest online pharmacy india – top online pharmacy india
Brazilian footballer Malcom https://al-hilal.malcom-ar.com (full name Malcom Felipe Silva de Oliveira) achieved great success in Al Hilal, one of the leading football teams in Saudi Arabia and the entire Middle East.
http://indiapharmast.com/# indian pharmacy paypal
pharmacies in mexico that ship to usa: purple pharmacy mexico price list – mexican pharmaceuticals online
medicine in mexico pharmacies mexican pharmacy medicine in mexico pharmacies
canada drugs reviews: escrow pharmacy canada – canadian world pharmacy