目录
问题
- 最近在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));
- 但最好还是直接用第一种,明确你使用正则的目的
reputable indian pharmacies indian pharmacy online buy prescription drugs from india
indian pharmacy paypal: reputable indian online pharmacy – reputable indian pharmacies
http://foruspharma.com/# mexico pharmacies prescription drugs
buy a cat in Israel
4israel (פורישראל) is a free message board in Israel, where visitors can publish and look for any information. We help users find everything they seek for life and promotion of business in Israel. You can find proposals for real estate, products, services, cars, sales announcements, work search, educational institutions and much more. Our site is the most popular languages in Israel, such as Hebrew, English, Russian and Arabic.
pharmacy website india: reputable indian pharmacies – indianpharmacy com
Monica Bellucci https://dracula.monica-bellucci-ar.com one of the most famous Italian actresses of our time, has a distinguished artistic career spanning many decades. Her talent, charisma, and stunning beauty made her an icon of world cinema.
Edson Arantes https://santos.pele-ar.com do Nascimento, known as Pele, was born on October 23, 1940 in Tres Coracoes, Minas Gerais, Brazil.
mexican pharmaceuticals online medication from mexico pharmacy mexican drugstore online
п»їlegitimate online pharmacies india: india pharmacy – reputable indian pharmacies
recommended canadian pharmacies: canadian pharmacy king reviews – vipps approved canadian online pharmacy
buying from online mexican pharmacy: mexico pharmacy – mexican pharmacy
Sadio Mane https://al-nassr.sadio-mane-ar.com the Senegalese footballer best known for his performances at clubs such as Southampton and Liverpool, has become a prominent figure in Al Nassr.
Brazilian footballer Ricardo Escarson https://orlando-city.kaka-ar.com dos Santos Leite, better known as Kaka, is one of the most famous and successful players in football history.
Bella Hadid https://img-models.bella-hadid-ar.com is an American model who has emerged in recent years as one of the most influential figures in the world of fashion.
http://canadapharmast.com/# canadian pharmacy drugs online
reputable mexican pharmacies online buying prescription drugs in mexico online medication from mexico pharmacy
mexican pharmaceuticals online buying prescription drugs in mexico online pharmacies in mexico that ship to usa
mexican pharmacy: best online pharmacies in mexico – buying from online mexican pharmacy
https://canadapharmast.online/# legal to buy prescription drugs from canada
buying from online mexican pharmacy: buying prescription drugs in mexico – buying prescription drugs in mexico
mexico pharmacy: mexican pharmaceuticals online – mexican rx online
purple pharmacy mexico price list: buying prescription drugs in mexico online – mexico drug stores pharmacies
http://foruspharma.com/# medicine in mexico pharmacies
mexican drugstore online: mexican drugstore online – buying from online mexican pharmacy
canada drug pharmacy maple leaf pharmacy in canada legitimate canadian pharmacy online
mail order pharmacy india: Online medicine order – indian pharmacy
canadian medications: reputable canadian online pharmacies – safe online pharmacies in canada
Kylie Jenner https://kylie-cosmetics.kylie-jenner-ar.com is an American model, media personality, and businesswoman, born on August 10, 1997 in Los Angeles, California.
Продажа новых автомобилей Hongqi
https://hongqi-krasnoyarsk.ru/about-hongqi в Красноярске у официального дилера Хончи. Весь модельный ряд, все комплектации, выгодные цены, кредит, лизинг, трейд-ин
Upcoming fantasy MOBA https://bladesofthevoid.com evolved by Web3. Gacha perks, AI and crafting in one swirling solution!
Казахский национальный технический университет https://satbayev.university им. К.Сатпаева
стоимость видеостены стоимость видеостены .
娛樂城優惠
Football in Saudi Arabia https://al-hilal.saud-abdulhamid-ar.com is gaining more and more popularity and recognition on the international stage, and Saud Abdul Hamid, the young and talented defender of Al Hilal, is a shining example of this success.
Khvicha Kvaratskhelia https://napoli.khvicha-kvaratskhelia-ar.com is a name that in recent years has become a symbol of Georgian football talent and ambition.
Angel Di Maria https://benfica.angel-di-maria-ar.com is a name that will forever remain in the memories of Benfica fans.
Roberto Firmino https://al-ahli.roberto-firmino-ar.com one of the most talented and famous Brazilian footballers of our time, has paved his way to success in different leagues and teams.
Maria Sharapova https://tennis.maria-sharapova-ar.com was born on April 19, 1987 in Nyagan, Russia. When Masha was 7 years old, her family moved to Florida, where she started playing tennis.
May I simply just say what a comfort to find someone that actually understands what they’re discussing on the internet. You certainly know how to bring an issue to light and make it important. More people ought to read this and understand this side of your story. I can’t believe you are not more popular since you definitely possess the gift.
casino cat
Muhammad Al Owais https://al-hilal.mohammed-alowais-ar.com is one of the most prominent names in modern Saudi football. His path to success in Al Hilal team became an example for many young athletes.
Kevin De Bruyne https://manchester-city.kevin-de-bruyne-ar.com is a name every football fan knows today.
Luis Diaz https://liverpool.luis-diaz-ar.com is a young Colombian striker who has enjoyed rapid growth since joining the ” Liverpool” in January 2022.
In 2018, the basketball world witnessed one of the most remarkable transformations in NBA history. LeBron James https://los-angeles-lakers.lebronjames-ar.com one of the greatest players of our time, decided to leave his hometown Cleveland Cavaliers and join the Los Angeles Lakers.
Cristiano Ronaldo https://al-nassr.cristiano-ronaldo.ae is one of the greatest names in football history, with his achievements inspiring millions of fans around the world.
Karim Benzema https://al-ittihad.karimbenzema.ae is a name worthy of admiration and respect in the world of football.
RDBox.de https://rdbox.de bietet schallgedammte Gehause fur 3D-Drucker, die eine sehr leise Druckumgebung schaffen – nicht lauter als ein Kuhlschrank. Unsere Losungen sorgen fur stabile Drucktemperatur, Vibrationsisolierung, Luftreinigung und mobile App-Steuerung.
Today, while I was at work, my cousin stole my iPad and tested to see if it can survive a twenty five foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views. I know this is completely off topic but I had to share it with someone!
lee bet регистрация
Kobe Bryant https://los-angeles-lakers.kobebryant-ar.com also known as the “Black Mamba”, is one of the most iconic and iconic figures in NBA history.
N’Golo Kante https://al-ittihad.ngolokante-ar.com the French midfielder whose career has embodied perseverance, hard work and skill, has continued his path to success at Al-Ittihad Football Club, based in Saudi Arabia.
Сайт https://ps-likers.ru предлагает уроки по фотошоп для начинающих. На страницах сайта можно найти пошаговые руководства по анимации, созданию графики для сайтов, дизайну, работе с текстом и фотографиями, а также различные эффекты.