目录
问题
- 最近在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));
- 但最好还是直接用第一种,明确你使用正则的目的
visit my website https://currencyconvert.net
Football in Saudi Arabia https://al-hilal.ali-al-bulaihi-ar.com has long been one of the main sports, attracting millions of fans. In recent years, one of the brightest stars in Saudi football has been Ali Al-Bulaihi, defender of Al-Hilal Football Club.
Luka Modric https://real-madrid.lukamodric-ar.com can certainly be called one of the outstanding midfielders in modern football.
Erling Haaland https://manchester-city.erling-haaland-ar.com born on July 21, 2000 in Leeds, England, began his football journey at an early age.
Brazilian footballer Neymar https://al-hilal.neymar-ar.com known for his unique playing style and outstanding achievements in world football, has made a surprise move to Al Hilal Football Club.
Harry Kane https://bayern.harry-kane-ar.com one of the most prominent English footballers of his generation, completed his move to German football club Bayern Munich in 2023.
vid-st http://www.internet-magazin-strojmaterialov.ru .
Yacine Bounou https://al-hilal.yassine-bounou-ar.com known simply as Bono, is one of the most prominent Moroccan footballers of our time.
Andreson Souza Conceicao https://al-nassr.talisca-ar.com known as Talisca, is one of the brightest stars of modern football.
The story of Leo Messi https://inter-miami.lionelmessi.ae‘s transfer to Inter Miami began long before the official announcement. Rumors about Messi’s possible departure from Barcelona appeared in 2020
Pedro Gonzalez Lopez https://barcelona.pedri-ar.com known as Pedri, was born on November 25, 2002 in the small town of Tegeste, located on Tenerife, one of the Canary Islands.
Hello would you mind sharing which blog platform you’re working with? I’m going to start my own blog soon but I’m having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique. P.S Sorry for being off-topic but I had to ask!
bocor88
Robert Lewandowski https://barcelona.robertlewandowski-ar.com is one of the most prominent footballers of our time, and his move to Barcelona has become one of the most talked about topics in world football.
Toni Kroos https://real-madrid.tonikroos-ar.com the German midfielder known for his accurate passes and calmness on the field, has achieved remarkable success at one of the most prestigious football clubs in the world.
Victor Osimhen https://napoli.victorosimhen-ar.com born on December 29, 1998 in Lagos, Nigeria, has grown from an initially humble player to one of the brightest strikers in modern football.
Vinicius Junior https://real-madrid.vinicius-junior-ar.com the Brazilian prodigy whose full name is Vinicius Jose Baixao de Oliveira Junior, has managed to win the hearts of millions of fans around the world in a short period of time.
bocor88 login
Earvin “Magic” Johnson https://los-angeles-lakers.magicjohnson.biz is one of the most legendary basketball players in history. NBA history.
Nuno Mendes https://paris-saint-germain.nuno-mendes.com, a talented Portuguese left-back, He quickly became one of the key figures in the Paris Saint-Germain (PSG) team.
Bruno Miguel Borges Fernandes https://manchester-united.brunofernandes-br.com was born on September 8, 1994 in Maia, Portugal.
Daniel Alves https://paris-saint-germain.danielalves.net is a name that symbolizes the greatness of the world of football.
Rodrygo Silva de Goes https://real-madrid.rodrygo-br.com, known simply as Rodrygo, emerged as one of the the brightest young talents in world football.
Anderson Silva https://killer-bees-muay-thai-college.andersonsilva.net was born in 1975 in Curitiba Brazil. From a young age he showed an interest in martial arts, starting to train in karate at the age of 5.
I genuinely prize your piece of work, Great post.
In the world of professional tennis, the name of Gustavo Kuerten https://roland-garros.gustavokuerten.com is closely linked to one of the most prestigious Grand Slam tournaments – Roland Garros.
Ayrton Senna https://mclaren.ayrtonsenna-br.com is one of the greatest drivers in the history of Formula 1.
Bieber’s https://baby.justinbieber-br.com path to global fame began with his breakthrough success Baby, which became his signature song and one of the most popular music videos of all time.
Achraf Hakimi https://paris-saint-germain.ashrafhakimi.net is a young Moroccan footballer who quickly reached the football elite European in recent years.
Kobe Bryant https://los-angeles-lakers.kobebryant-br.net one of the greatest basketball players of all the times, left an indelible mark on the history of sport.
Selena Gomez https://calm-down.selenagomez-br.net the story from child star to global musical influence, summarized in hit “Calm Down”, with Rema.
Fabrizio Moretti https://the-strokes.fabriziomoretti-br.com the influential drummer of The Strokes, and his unique sound revolutionized the music scene, remaining icons of modern rock.
A historia da jornada triunfante de Anitta https://veneno.anitta-br.com de aspirante a cantora a uma das interpretes mais influentes da musica moderna, incluindo sua participacao na serie de TV “Veneno”.
In-depth articles about the most famous football players https://zenit-saint-petersburg.wendel-br.com, clubs and events. Learn everything about tactics, rules of the game and football history.
The rise of 20-year-old midfielder Jamal Musiala https://bavaria.jamalmusiala-br.com to the status of a winger in the Bayern Munich team. A story of incredible talent.
Midfielder Rafael Veiga leads https://manchester-city.philfoden-br.com Palmeiras to success – the championship Brazilian and victory in the Copa Libertadores at the age of 24.
O meio-campista Rafael Veiga leva https://palmeiras.raphaelveiga-br.com o Palmeiras ao sucesso – o campeonato brasileiro e a vitoria na Copa Libertadores aos 24 anos.
The incredible story https://napoli.khvichakvaratskhelia-br.com of a young Georgian talent’s transformation into an Italian Serie A star. Khvicha Kvaraeshvili is a rising phenomenon in European football.
The compelling story of Alisson Becker’s https://bayer-04.florianwirtz-br.com meteoric rise from young talent to key figure in Liverpool’s triumphant era under Jurgen Klopp.
The incredible success story of 20-year-old Florian Wirtz https://bayer-04.florianwirtz-br.com, who quickly joined the Bayer team and became one of the best young talents in the world.
Геракл24: Опытная Реставрация Фундамента, Венцов, Настилов и Передвижение Строений
Организация Геракл24 специализируется на выполнении комплексных услуг по замене основания, венцов, полов и перемещению строений в городе Красноярском регионе и за пределами города. Наш коллектив квалифицированных специалистов обещает высокое качество реализации различных типов реставрационных работ, будь то из дерева, каркасные, кирпичные постройки или из бетона здания.
Преимущества услуг Геракл24
Квалификация и стаж:
Все работы выполняются исключительно высококвалифицированными специалистами, с обладанием многолетний практику в области возведения и реставрации домов. Наши мастера эксперты в своей области и выполняют задачи с максимальной точностью и вниманием к деталям.
Комплексный подход:
Мы предоставляем полный спектр услуг по ремонту и реконструкции строений:
Реставрация фундамента: усиление и реставрация старого основания, что обеспечивает долгий срок службы вашего здания и предотвратить проблемы, связанные с оседанием и деформацией строения.
Замена венцов: реставрация нижних венцов из дерева, которые наиболее часто гниют и разрушаются.
Установка новых покрытий: установка новых полов, что существенно улучшает внешний облик и практическую полезность.
Передвижение домов: безопасное и надежное перемещение зданий на другие участки, что помогает сохранить здание и избегает дополнительных затрат на создание нового.
Работа с любыми типами домов:
Древесные строения: восстановление и укрепление деревянных конструкций, защита от гниения и вредителей.
Каркасные строения: укрепление каркасов и смена поврежденных частей.
Дома из кирпича: восстановление кирпичной кладки и укрепление стен.
Бетонные строения: реставрация и усиление бетонных элементов, исправление трещин и разрушений.
Качество и надежность:
Мы работаем с только проверенные материалы и новейшее оборудование, что обеспечивает долгий срок службы и надежность всех работ. Все проекты подвергаются строгому контролю качества на каждом этапе выполнения.
Индивидуальный подход:
Мы предлагаем каждому клиенту индивидуальные решения, учитывающие все особенности и пожелания. Мы стремимся к тому, чтобы конечный результат полностью удовлетворял вашим запросам и желаниям.
Почему стоит выбрать Геракл24?
Обратившись к нам, вы получаете надежного партнера, который берет на себя все заботы по восстановлению и ремонту вашего здания. Мы обеспечиваем выполнение всех задач в сроки, оговоренные заранее и с соблюдением всех строительных норм и стандартов. Выбрав Геракл24, вы можете быть уверены, что ваше строение в надежных руках.
Мы предлагаем консультацию и ответить на ваши вопросы. Свяжитесь с нами, чтобы обсудить детали вашего проекта и узнать о наших сервисах. Мы поможем вам сохранить и улучшить ваш дом, сделав его безопасным и комфортным для проживания на долгие годы.
Геракл24 – ваш партнер по реставрации и ремонту домов в Красноярске и окрестностях.
https://gerakl24.ru/поднять-дом-красноярск/
Ousmane Dembele’s https://paris-saint-germain.ousmanedembele-br.com rise from promising talent to key player for French football giants Paris Saint-Germain. An exciting success story.
The fascinating story of Sergio Ramos’ https://seville.sergioramos.net rise from Sevilla graduate to one of Real Madrid and Spain’s greatest defenders.
Пансионаты для пожилых людей https://moyomesto.ru в Самаре по доступным ценам. Специальные условия по уходу, индивидуальные программы.
Лучшие пансионаты для пожилых людей https://ernst-neizvestniy.ru в Самаре – недорогие дома для престарелых в Самарской области
Хотите научиться готовить самые изысканные и сложные торты? В этом https://v1.skladchik.org/tags/tort/ разделе вы найдете множество подробных пошаговых рецептов самых трендовых и известных тортов с возможностью получить их за сущие копейки благодаря складчине. Готовьте с удовольствием и открывайте для себя новые рецепты вместе с Skladchik.org
сайт драгон мани казино бонус драгон мани казино
онлайн казино Dragon Money uvstyle.ru
официальный сайт Rio Bet Casino https://dacha76.ru
казино риобет сайт казино рио бет