目录
问题
- 最近在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://uamc.com.ua про Україну від порталу новин Ukraine Today
You really make it seem really easy along with your presentation however I find this matter to be actually something which I feel I’d never understand. It sort of feels too complex and extremely broad for me. I am having a look ahead on your next publish, I’ll attempt to get the grasp of it!
Останні новини https://thingshistory.com зовнішньої та внутрішньої політики в країні та світі.
Головні новини https://status.net.ua сьогодні, найсвіжіші та останні новини України онлайн
Корисні та цікаві статті https://sevsovet.com.ua про здоров’я, дозвілля, кар’єру.
Новини, останні події https://prp.org.ua в Україні та світі, новини політики, бізнесу та економіки, законодавства
Новини України https://sensus.org.ua та світу сьогодні. Головні та останні новини дня
Головні новини https://mediashare.com.ua про регіон України. Будьте в курсі останніх новин
Новини та аналітика https://newsportal.kyiv.ua ситуація в Україні.
Головні новини https://pto-kyiv.com.ua України та світу
coindarwin price analysis
The Unseen Narrative About Solana’s Founder Toly’s Triumph
Subsequent to Two Servings of Espresso with a Pint
Yakovenko, the mastermind behind Solana, initiated his venture with a simple routine – two cups of coffee and a beer. Unaware to him, these occasions would trigger the cogs of fate. At present, Solana is as a significant participant in the crypto space, with a market cap in the billions.
Ethereum ETF First Sales
The new Ethereum ETF lately launched with a staggering trading volume. This historic event experienced several spot Ethereum ETFs from different issuers start trading on U.S. markets, creating unprecedented activity into the typically steady ETF trading space.
SEC’s Approval of Ethereum ETF
The Commission has formally approved the Ethereum ETF to trade. As a crypto asset featuring smart contracts, it is expected that Ethereum to majorly affect the blockchain sector due to this approval.
Trump’s Crypto Maneuver
With the election nearing, Trump portrays himself as the “President of Crypto,” repeatedly showing his backing of the digital currency sector to attract voters. His tactic differs from Biden’s approach, seeking to capture the support of the digital currency community.
Elon Musk’s Influence
Elon Musk, a prominent figure in the digital currency sector and an advocate of Trump, shook things up yet again, promoting a meme coin linked to his antics. His involvement keeps shaping market trends.
Binance’s Latest Moves
Binance’s subsidiary, BAM, is now permitted to invest customer funds in U.S. Treasury securities. Moreover, Binance celebrated its 7th year, showcasing its development and securing several compliance licenses. Simultaneously, the firm also made plans to take off several important cryptocurrency pairs, affecting different market players.
Artificial Intelligence and Economic Outlook
The chief stock analyst at Goldman Sachs recently observed that artificial intelligence won’t lead to an economic revolution
you could have an excellent weblog here! would you prefer to make some invite posts on my blog?
Україна останні новини https://lentanews.kyiv.ua головні новини та останні події
Свіжі новини України https://lenta.kyiv.ua останні новини з-за кордону, новини політики, економіки, спорту, культури.
Популярные репортажи https://infotolium.com в больших фотографиях, новости, события в мире
Україна свіжі новини https://kiev-pravda.kiev.ua останні події на сьогодні
Новини України https://kiev-online.com.ua останні події в Україні та світі сьогодні, новини України за минулий день онлайн
Новинний ресурс https://actualnews.kyiv.ua про всі важливі події в Україні та світі.
Новини сьогодні https://gau.org.ua останні новини України та світу онлайн
продвижение бизнеса в интернете под ключ https://seooptimizatsia.ru
сколько стоит продвижение сайта и оптимизация сайта сколько стоит сео продвижение сайта в месяц
The Hidden Account Regarding Solana’s Founder Toly’s Triumph
Following Two Portions of Coffees plus a Pint
Yakovenko, the visionary the visionary behind Solana, started his journey with a modest routine – two cups of coffee and a beer. Little did he realize, these moments would spark the wheels of his journey. Currently, Solana remains as an influential participant in the blockchain space, boasting a market value of billions.
Ethereum ETF First Sales
The Ethereum ETF just made its debut with a staggering trading volume. This historic event witnessed various spot Ethereum ETFs from multiple issuers be listed on U.S. exchanges, bringing unseen activity into the typically steady ETF trading space.
Ethereum ETF Approval by SEC
The U.S. SEC has formally approved the Ethereum Spot ETF to trade. As a digital asset featuring smart contracts, Ethereum is expected to significantly impact the blockchain sector due to this approval.
Trump’s Bitcoin Strategy
As the election approaches, Trump frames himself as the “President of Crypto,” constantly highlighting his support for the crypto sector to gain voters. His approach contrasts with Biden’s approach, aiming to capture the interest of the crypto community.
Elon Musk’s Crypto Moves
Elon, a famous figure in the cryptocurrency space and an advocate of Trump, created a buzz once again, promoting a meme coin connected to his actions. His participation keeps influencing market dynamics.
Binance’s Latest Moves
A subsidiary of Binance, BAM, is now allowed to allocate customer funds in U.S. Treasuries. Furthermore, Binance noted its 7th anniversary, emphasizing its journey and achieving numerous regulatory approvals. At the same time, the company also made plans to remove several significant crypto trading pairs, affecting different market players.
AI and Economic Trends
A top stock analyst from Goldman Sachs recently mentioned that AI is unlikely to cause an economic revolution
переговорные комнаты под ключ переговорные комнаты под ключ .
конференц залы оборудование конференц залы оборудование .
ключ от комнаты совещаний ключ от комнаты совещаний .
The Unseen Narrative About Solana’s Founder Toly’s Accomplishment
Subsequent to 2 Mugs of Java and a Brew
Toly, the mastermind behind Solana, commenced his journey with a routine practice – coffee and beer. Little did he know, these moments would set the cogs of his journey. Currently, Solana exists as an influential player in the cryptocurrency space, having a market cap in the billions.
Ethereum ETF First Sales
The new Ethereum ETF recently started with an impressive trade volume. This milestone event witnessed several spot Ethereum ETFs from several issuers start trading on U.S. markets, bringing extraordinary activity into the usually calm ETF trading environment.
SEC Approved Ethereum ETF
The SEC has officially approved the Ethereum exchange-traded fund to be listed. As a cryptographic asset with smart contracts, Ethereum is anticipated to significantly impact the digital currency industry following this approval.
Trump’s Crypto Maneuver
As the election draws near, Trump portrays himself as the “Crypto President,” frequently displaying his backing of the digital currency sector to garner votes. His method contrasts with Biden’s strategy, intending to capture the support of the digital currency community.
Elon Musk’s Crypto Moves
Elon Musk, a well-known figure in the digital currency sector and a backer of Trump, created a buzz once more, driving a meme coin associated with his antics. His actions keeps shaping market dynamics.
Binance Updates
Binance’s unit, BAM, is now allowed to channel customer funds into U.S. Treasuries. Moreover, Binance celebrated its 7th anniversary, highlighting its journey and acquiring various compliance licenses. Simultaneously, the corporation also made plans to remove several significant crypto trading pairs, altering the market landscape.
Artificial Intelligence and Economic Outlook
Goldman Sachs’ top stock analyst recently mentioned that AI won’t spark a major economic changeHere’s the spintax version of the provided text with possible synonyms
онлайн продвижение https://seo-raskrutka43.ru
поисковое продвижение заказать сео раскрутка
Помощь студентам в выполнении рефератов https://referatkupit-oline.ru. Низкие цены и быстрое написание рефератов!
Красивая музыка https://melodia.space для души слушать онлайн.
Accessibility Team Meeting Notes https://make.wordpress.org/accessibility/2021/06/11/accessibility-team-meeting-notes-june-11-2021