目录
问题
- 最近在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));
- 但最好还是直接用第一种,明确你使用正则的目的
Заказать курсовую работу https://kursovye-napishem.ru в Москве: цены на написание и выполнение, недорого
Заказать дипломную работу https://diplomzakazat-oline.ru недорого. Дипломные работы на заказ с гарантией.
купить 1 комнатную новостройку купить 2 квартиру новостройке
Заказать контрольную работу https://kontrolnye-reshim.ru, недорого, цены. Решение контрольных работ на заказ срочно.
Помощь в решении задач https://zadachireshaem-online.ru. Опытные авторы с профессиональной подготовкой окажут консультацию в решении задач на заказ недорого, быстро, качественно
купить новостройку с ремонтом https://kvartiranovostroi2.ru
новостройки купить цены купить однокомнатную квартиру
coindarwin web3 academy
The Unseen Account Regarding Solana Founder Toly Yakovenko’s Success
Subsequent to Two Mugs of Coffees plus a Ale
Yakovenko, the visionary the visionary behind Solana, initiated his path with a simple habit – a couple of coffees and an ale. Unbeknownst to him, those moments would trigger the machinery of his future. At present, Solana exists as a significant player in the digital currency space, boasting a billion-dollar market value.
Ethereum ETF Debut
The Ethereum ETF newly was introduced with a substantial volume of trades. This milestone event saw various spot Ethereum ETFs from various issuers start trading in the U.S., creating significant activity into the usually calm ETF trading environment.
Ethereum ETF Approval by SEC
The U.S. SEC has sanctioned the spot Ethereum ETF to trade. As a digital asset with smart contracts, Ethereum is expected to significantly impact on the cryptocurrency industry with this approval.
Trump’s Bitcoin Tactics
As the election approaches, Trump positions himself as the ‘Cryptocurrency President,’ frequently displaying his backing of the cryptocurrency industry to garner votes. His method is different from Biden’s tactic, intending to capture the interest of the blockchain community.
Elon Musk’s Influence
Elon, a prominent figure in the blockchain world and a supporter of Trump, created a buzz once again, boosting a meme coin linked to his antics. His engagement keeps influencing market trends.
Binance’s Latest Moves
Binance’s subsidiary, BAM, has been permitted to channel customer funds into U.S. Treasury instruments. In addition, Binance observed its 7th year, underscoring its path and obtaining various compliance licenses. In the meantime, the corporation also made plans to delist several notable cryptocurrency trading pairs, influencing multiple market entities.
AI and Economic Trends
Goldman Sachs’ top stock analyst recently stated that artificial intelligence won’t lead to a revolution in the economy
белый список капперов телеграмм http://rejting-kapperov12.ru/ .
новые квартиры от застройщиков https://zastroyshikekb.ru
квартиры с отделкой от застройщика недвижимость купить квартиру
купить квартиру в новостройке цены купить новостройку в ипотеку
недвижимость купить квартиру https://novyekvartiry2.ru
купить новую квартиру в новостройке купить новостройку от застройщика
квартира в новостройке от застройщика https://kvartirukupit43.ru
квартиры с отделкой от застройщика https://novye-kvartiry-spb.ru
купить двухкомнатную квартиру в новостройке https://novye-kvartiryspb.ru
amoxicillin without prescription: amoxicillin 250 mg – buy amoxicillin canada
where can i buy amoxicillin over the counter: amoxicillin for sale – buy amoxicillin 500mg uk
buy amoxicillin over the counter uk: amoxicillin from canada – where can i get amoxicillin
Indibet is a premier online casino offering a wide array of games including slots, table games, and live dealer options. Renowned for its user-friendly interface and robust security measures, Indibet ensures a top-notch gaming experience with exciting bonuses and 24/7 customer support.
купить квартиру в новостройке https://kvartiru-kupit43.ru
купить 1 комнатную новостройку https://kvartira-new43.ru
купить новую квартиру застройщик купить однокомнатную квартиру
The future football star Shabab Al-Ahly https://dubai.shabab-al-ahli-ar.com was born in Dubai in 2000. From a young age, he showed exceptional football abilities and joined the youth academy of one of the UAE’s leading clubs, Shabab Al-Ahly.
In the world of football, Atletico Madrid https://spain.atletico-madrid-ar.com has long been considered the second most important club in Spain after the dominant, Real Madrid.
The fascinating story of Ja Morant’s https://spain.atletico-madrid-ar.com meteoric rise, from status from rookie to leader of the Memphis Grizzlies and rising NBA superstar.
Galatasaray https://turkey.galatasaray-ar.com is one of the most famous football clubs in Turkiye, with a glorious and eventful history.
can i order cheap clomid no prescription: get clomid without rx – where can i buy clomid pills
AC Milan https://italy.milan-ar.com is one of the most successful and decorated football clubs in the world.
Ремонт плоской кровли https://remontiruem-krovly.ru в Москве, цена работы за 1 м?. Прайс лист на работы под ключ, отзывы и фото.
брендированные бумажные пакеты типография телефон
Thai Company Directory https://thaicorporates.com List of companies and business information.
ciprofloxacin generic: п»їcipro generic – buy ciprofloxacin
buy doxycycline 500mg: doxycycline online usa – doxycycline prescription canada
Real Madrid’s https://spain.real-madrid-ar.com history goes back more than a century. The club was founded in 1902 by a group of football enthusiasts led by Juan Padilla
Arsenal https://england.arsenal-ar.com is one of the most famous and successful football clubs in the history of English football.
FC Bayern Munich (Munich) https://germany.bayern-munchen-ar.com is one of the most famous and recognized football clubs in Germany and Europe
raffaelli 40 https://rent-a-yacht-montenegro.com
Montenegro boat tour rent a boat Montenegro
золотая коллекция порно https://porn-library.ru/ .
http://ciprodelivery.pro/# ciprofloxacin mail online
https://clomiddelivery.pro/# how to buy generic clomid no prescription
amoxicillin 500mg pill: cost of amoxicillin 875 mg – where can i buy amoxicillin without prec
buy cipro: buy cipro online canada – cipro
FC Barcelona https://spain.fc-barcelona-ar.com is undoubtedly one of the most famous and well-known football clubs in the world.
Al-Nasr Club https://saudi.al-hilal-ar.com from Riyadh has a rich history of success, but its growth has been particularly impressive in recent years.
Al-Ittihad https://saudi.al-ittihad-ar.com is one of the most famous football clubs in Saudi Arabia. Founded in 1927, the Saudi football giant has come a long way to the pinnacle of success.
Al-Nasr https://saudi.al-nassr-ar.com is one of the most famous football teams in the Kingdom of Saudi Arabia.
http://amoxildelivery.pro/# where to buy amoxicillin 500mg