目录
问题
- 最近在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));
- 但最好还是直接用第一种,明确你使用正则的目的
Luis Suarez https://inter-miami.luis-suarez-ar.com the famous Uruguayan footballer, ended his brilliant career in European clubs and decided to try his hand at a new challenge – Major League Soccer.
where can i buy amoxicillin online: amoxicillin price canada – order amoxicillin online uk
https://doxycyclinedelivery.pro/# doxycycline 25mg tablets
смотреть классное порево смотреть классное порево .
http://amoxildelivery.pro/# amoxicillin 500mg price in canada
механизм подъема грузового подъемника грузовой подъемник для склада
Bayern Munich’s https://bayern.jamal-musiala-ar.com young midfielder, Jamal Musiala, has become one of the brightest talents in European football.
Thibaut Courtois https://real-madrid.thibaut-courtois-ar.com was born on May 11, 1992 in Belgium.
angkot88
doxycycline nz: doxycycline pills – no prescription doxycycline
http://paxloviddelivery.pro/# paxlovid pill
It’s awesome to pay a visit this web site and reading the views of all colleagues regarding this article, while I am also keen of getting know-how.
tatar.org.ru
Arsenal https://arsenal.mesut-ozil-ar.com made a high-profile signing in 2013, signing star midfielder Mesut Ozil from Real Madrid.
https://doxycyclinedelivery.pro/# doxycycline 250
https://euroavia24.com – Cheap flights, hotels and transfers around the world!
I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an impatience over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase.
https://thetvdb.plex.tv/movies/real-gangsters
Rodrigo Goes https://real-madrid.rodrygo-ar.com better known as Rodrigo, is one of the brightest young talents in modern football.
The Saudi Football League https://saudi-arabian-championship.saudi-pro-league-ar.com known as the Saudi Professional League, is one of the most competitive and dynamic leagues in the world.
In an era when many young footballers struggle to find their place at elite clubs, Javi’s https://barcelona.gavi-ar.com story at Barcelona stands out as an exceptional one.
cipro 500mg best prices: cipro for sale – cipro for sale
I have been exploring for a little bit for any high quality articles or blog posts in this sort of area . Exploring in Yahoo I eventually stumbled upon this web site. Reading this info So i am glad to convey that I have an incredibly good uncanny feeling I discovered just what I needed. I so much certainly will make certain to do not fail to remember this website and give it a glance on a relentless basis.
Thank you for sharing superb informations. Your web-site is very cool. I’m impressed by the details that you¦ve on this website. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for extra articles. You, my pal, ROCK! I found just the info I already searched all over the place and just couldn’t come across. What an ideal web-site.
In recent years, the leading positions in the Spanish https://spanish-championship.laliga-ar.com championship have been firmly occupied by two major giants – Barcelona and Real Madrid.
In the German football https://german-championship.bundesliga-football-ar.com championship known as the Bundesliga, rivalries between clubs have always been intense.
The Italian football championship https://italian-championship.serie-a-ar.com known as Serie A, has seen an impressive revival in recent years.
The road to the Premier League https://english-championship.premier-league-ar.com begins long before a team gets promoted to the English Premier League for the first time
The golf https://arabic.golfclub-ar.com industry in the Arab world is growing rapidly, attracting players from all over the world.
ciprofloxacin over the counter: buy ciprofloxacin – buy cipro
https://amoxildelivery.pro/# buy amoxicillin online cheap
http://amoxildelivery.pro/# buy amoxicillin online with paypal
https://clomiddelivery.pro/# cost of clomid online
Temp Mail This was beautiful Admin. Thank you for your reflections.
самое лучшее порево https://besplatny-sex-online.ru .
https://ciprodelivery.pro/# ciprofloxacin 500 mg tablet price
where can i buy cheap clomid without insurance: can i purchase clomid – cost of clomid no prescription
Manny Pacquiao https://filipino-boxer.manny-pacquiao-ar.com is one of the most prominent boxers in the history of the sport.
https://paxloviddelivery.pro/# paxlovid generic
Muhammad Ali https://american-boxer.muhammad-ali-ar.com is perhaps one of the most famous and greatest athletes in the history of boxing.
Mike Tyson https://american-boxer.mike-tyson-ar.com one of the most famous and influential boxers in history, was born on June 30, 1966 in Brooklyn, New York.
luxury car rental Montenegro renting a car in Montenegro
doxycycline online pharmacy canada: doxycycline tablets online india – buy generic doxycycline 40mg
Michael Jordan https://chicago-bulls.michael-jordan-ar.com is one of the greatest basketball players of all time, whose career with the Chicago Bulls is legendary.
прихожая дизайн интерьера спальня дизайн интерьера
The Formula One World Championship https://world-circuit-racing-championship.formula-1-ar.com, known as the Formula Championship in motor racing, is the highest tier of professional motor racing.
After some difficult years in the late 2010s, Manchester United https://england.manchester-united-ar.com returned to greatness in English football by 2024.
http://clomiddelivery.pro/# how to get cheap clomid tablets
https://ciprodelivery.pro/# п»їcipro generic
buy paxlovid online: paxlovid pill – paxlovid buy
Jennifer Lopez https://lets-get-loud.jenniferlopez-ar.com was born in 1969 in the Bronx, New York, to parents who were Puerto Rican immigrants.
лучшее порно видео онлайн бесплатно лучшее порно видео онлайн бесплатно .