Содержание
- Python Regex Multiple Repeat Error
- How Does the Multiple Repeat Error Arise in Python Re?
- [Tips] What’s the Source of the Multiple Repeat Error and How to Avoid It?
- Python Regex Quantifiers
- Alternative Error Message (Fragments)
- Where to Go From Here?
- Regex Humor
- Python Regex Несколько повторной ошибки повторения
- Как возникает множественная повторяющаяся ошибка в Python Re?
- [Советы] Как источник ошибки нескольких повторов и как его избежать?
- Python Regex Quebifiers
- Альтернативное сообщение об ошибке (фрагменты)
- Куда пойти отсюда?
Python Regex Multiple Repeat Error
Just like me an hour ago, you’re probably sitting in front of your regular expression code, puzzled by a strange error message:
Why is it raised? Where does it come from? And, most importantly, how can you get rid of it?
This article gives you answers to all of those questions. Alternatively, you can also watch my short explainer video that shows you real quick how to resolve this error:
How Does the Multiple Repeat Error Arise in Python Re?
Python’s regex library re throws the multiple repeat error when you stack two regex quantifiers on top of each other. For example, the regex pattern ‘a++’ will cause the multiple repeat error. You can get rid of this error by avoiding to stack quantifiers on top of each other.
Here’s an example:
I have shortened the error message to focus on the relevant parts. In the code, you first import the regex library re . You then use the re.findall(pattern, string) function (see this blog tutorial) to find the pattern ‘a++’ in the string ‘aaaa’ .
However, this doesn’t make a lot of sense: what’s the meaning of the pattern a++ anyway? Having a single quantifier a+ already reads as “find all matches where at least one character ‘a’ matches”.
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
[Tips] What’s the Source of the Multiple Repeat Error and How to Avoid It?
The error happens if you use the Python regex package re . There are many different reasons but all of them have the same source: you stack quantifiers on top of each other.
If you don’t know what a quantifier is, scroll down and read the following subsection where I show you exactly what it is.
Here’s a list of reasons for the error message. Maybe your reason is among them?
- You use the regex pattern ‘X++’ for any regex expression X . To avoid this error, get rid of one quantifier.
- You use the regex pattern ‘X+*’ for any regex expression X . To avoid this error, get rid of one quantifier.
- You use the regex pattern ‘X**’ for any regex expression X . To avoid this error, get rid of one quantifier.
- You use the regex pattern ‘X*’ for any regex expression X and number of repetitions m and n . To avoid this error, get rid of one quantifier.
- You try to match a number of characters ‘+’ and use a second quantifier on top of it such as ‘+?’ . In this case, you should escape the first quantifier symbol ‘+’ .
- You try to match a number of characters ‘*’ and use a second quantifier on top of it such as ‘*+’ . Avoid this error by escaping the first quantifier symbol ‘*’ .
Oftentimes, the error appears if you don’t properly escape the special quantifier meta-characters in your regex pattern.
Here’s a StackOverflow post that shows some code where this happened:
I edited the given code snippet to show the important part. The code fails because of a multiple repeat error . Can you see why?
The reason is that the regex ‘lg incite» OR author:»http++www.dealitem.com» OR «for sale’ contains two plus quantifiers stacked on top of each other in the substring ‘http++’ . Get rid of those and the code will run again!
Python Regex Quantifiers
The word “quantifier“ originates from latin: it’s meaning is quantus = how much / how often.
This is precisely what a regular expression quantifier means: you tell the regex engine how often you want to match a given pattern.
If you think you don’t define any quantifier, you do it implicitly: no quantifier means to match the regular expression exactly once.
So what are the regex quantifiers in Python?
Quantifier | Meaning |
A? | Match regular expression A zero or one times |
A* | Match regular expression A zero or more times |
A+ | Match regular expression A one or more times |
A | Match regular expression A exactly m times |
A | Match regular expression A between m and n times (included) |
Note that in this tutorial, I assume you have at least a remote idea of what regular expressions actually are. If you haven’t, no problem, check out my detailed regex tutorial on this blog.
You see in the table that the quantifiers ? , * , + , , and define how often you repeat the matching of regex A .
Let’s have a look at some examples—one for each quantifier:
In each line, you try a different quantifier on the same text ‘aaaa’ . And, interestingly, each line leads to a different output:
- The zero-or-one regex ‘a?’ matches four times one ‘a’ . Note that it doesn’t match zero characters if it can avoid doing so.
- The zero-or-more regex ‘a*’ matches once four ‘a’ s and consumes them. At the end of the string, it can still match the empty string.
- The one-or-more regex ‘a+’ matches once four ‘a’ s. In contrast to the previous quantifier, it cannot match an empty string.
- The repeating regex ‘a<3>‘ matches up to three ‘a’ s in a single run. It can do so only once.
- The repeating regex ‘a<1,2>‘ matches one or two ‘a’ s. It tries to match as many as possible.
You’ve learned the basic quantifiers of Python regular expressions.
Alternative Error Message (Fragments)
You may encounter any of the following fragments that all lead to the multiple repeat error:
- re.error: multiple repeat at position
- multiple repeat at position
- sre_constants.error: multiple repeat
- python regex multiple repeat
- python re multiple repeat
- regex multiple repeat
- re.error multiple repeat at position
Again, you can fix the multiple repeat error by avoiding to stack two regex quantifiers on top of each other. For example, the regex pattern ‘a++’ will cause the multiple repeat error—use a single quantifier such as ‘a+’ instead.
Where to Go From Here?
To summarize, you’ve learned that the multiple repeat error appears whenever you try to stack multiple quantifiers on top of each other. Avoid this and the error message will disappear.
If you want to boost your Python regex skills to the next level, check out my free in-depth regex superpower tutorial (20,000+) words. Or just bookmark the article for later read.
Regex Humor
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Источник
Python Regex Несколько повторной ошибки повторения
Так же, как я час назад, вы, вероятно, сидите перед вашим регулярным кодом выражения, озадачены странным сообщением об ошибке: Re.Error: несколько повторите в положении x Почему он поднимает? Откуда это взялось? И, самое главное, как вы можете избавиться от этого? Эта статья дает вам ответы на все … Python Regeex Несколько повторной ошибки повторения Подробнее »
Автор: Chris
Дата записи
Автор оригинала: Chris.
Также как я час назад, вы, вероятно, сидите перед вашим регулярным кодом выражения, озадачены странным сообщением об ошибке:
Почему это подняло? Откуда это взялось? И, самое главное, как вы можете избавиться от этого?
Эта статья дает вам ответы на все эти вопросы. В качестве альтернативы вы также можете посмотреть мое короткое видео об объяснении, которое показывает вам реальный, как разрешить эту ошибку:
Связанная статья: Python Regex SuperPower – Ultimate Guide
Как возникает множественная повторяющаяся ошибка в Python Re?
Python’s Regex Библиотека Re бросает несколько ошибок повторения, когда вы стекаете два квантализатора Regex друг на друге. Например, рисунок Regex ‘A ++’ приведет к нескольким повторной ошибке. Вы можете избавиться от этой ошибки, избегая, чтобы стечь количественными квантами друг на друга.
Я сократил сообщение об ошибке, чтобы сосредоточиться на соответствующих частях. В коде вы впервые импортируете библиотеку Regex Re Отказ Вы тогда используете Re.findall (шаблон, строка) Функция ( См. Учебное пособие в блоге ) Чтобы найти шаблон ‘A ++’ В строке «АААА» Отказ
Однако это не имеет большого смысла: в чем смысл шаблона a++ в любом случае? Имея один квантификатор A + уже читает как «Найти все матчи, где хотя бы один символ ‘A’ Матчи» Отказ
Вы хотите освоить сверхдержаву Regeex? Проверьте мою новую книгу Самый умный способ изучать регулярные выражения в Python С инновационным 3-ступенчатым подходом для активного обучения: (1) Изучение книги главы, (2) Решите головоломки кода и (3) Смотреть воспроизведение главы видео.
[Советы] Как источник ошибки нескольких повторов и как его избежать?
Ошибка происходит, если вы используете Python Regex Пакет Re Отказ Есть много разных причин, но все они имеют одинаковый источник: вы стекаете количественные кванты друг на друга друг на друга.
Если вы не знаете, что такое квантификатор, прокрутите вниз и прочитайте следующий подраздел, где я показываю, что именно то, что оно есть.
Вот список причин для сообщения об ошибке. Может быть, ваша причина в том числе?
- Вы используете шаблон Regex ‘X ++’ Для любого выражения Regex X . Чтобы избежать этой ошибки, избавьтесь от одного квантификатора.
- Вы используете шаблон Regex ‘Х + *’ Для любого выражения Regex X . Чтобы избежать этой ошибки, избавьтесь от одного квантификатора.
- Вы используете шаблон Regex ‘X **’ Для любого выражения Regex X . Чтобы избежать этой ошибки, избавьтесь от одного квантификатора.
- Вы используете шаблон Regex ‘X *’ Для любого выражения Regex Х и количество повторений м и N Отказ Чтобы избежать этой ошибки, избавьтесь от одного квантификатора.
- Вы пытаетесь сопоставить ряд персонажей ‘+’ и используйте второй квантификатор поверх этого, как ‘+?’ . В этом случае вы должны избежать первого символа квантификатора ‘ +’ Отказ
- Вы пытаетесь сопоставить ряд персонажей ‘*’ и используйте второй квантификатор поверх этого, как ‘* +’ Отказ Избегайте этой ошибки, избегая первого символа квантификатора ‘ *’ Отказ
Часто ошибка появляется, если вы не избежите специального квантификатора мета-символов в вашем рисунке Regex.
Вот a Stackoverflow Пост, который показывает какой-то код, где это произошло:
Я отредактировал данный фрагмент кода, чтобы показать важную роль. Код терпит неудачу из-за Ошибка нескольких повторов . Вы видите почему?
Причина в том, что регеекс «LG Incite» или автор: «HTTP ++ www.dealitem.com» или «на продажу ‘ Содержит два плюс количественных квантов, сложенных друг на друга в подстроке ‘http ++’ Отказ Избавьтесь от тех, и код снова запустится!
Python Regex Quebifiers
Слово “ квантификатор “ Возникает из латыни: это значение Кванс много/Как часто Отказ
Это именно то, что означает регулярное определение количества выражений: вы сообщите двигателю REGEX, как часто вы хотите сопоставить данный шаблон.
Если вы считаете, что вы не определяете какой-либо квантификатор, вы делаете это неявно: никакого количества означает совпадение регулярного выражения ровно.
Так Каковы квантования Regeex в Python?
Квантификатор | Имея в виду |
А? | Сопоставить регулярное выражение ноль или один раз |
A* | Сопоставить регулярное выражение нуля или более раз |
A+ | Сопоставить регулярное выражение единое или несколько раз |
Являюсь> | Соответствовать регулярному выражению точно M раз |
A | Соответствовать регулярному выражению между m и n раз (включая) |
Обратите внимание, что в этом руководстве я предполагаю, что у вас есть хотя бы удаленное представление о том, какие регулярные выражения на самом деле являются. Если у вас нет проблем, не ознакомьтесь с моим подробным руководством REGEX в этом блоге.
Вы видите в таблице, что квантаторы ? , * , + , <м>и Определите, как часто вы повторяете сопоставление Regex A .
Давайте посмотрим на некоторые примеры – один для каждого квантификатора:
В каждой строке вы попробуйте другой квантификатор на одном тексте «АААА» Отказ И, интересно, каждая строка приводит к другому выходу:
- нулевой или один Regex ‘а? соответствует четыре раза один «А» Отказ Обратите внимание, что он не соответствует нулевым символам, если он может избежать этого.
- ноль или-другое Regex « A * ‘ совпадает раз в четырех «А» и поглощает их. В конце строки он все еще может сравниться с пустой строкой.
- одно- или больше Regex ‘A +’ совпадает раз в четырех «А» s. В отличие от предыдущего квантификатора, он не может сравниться с пустой строкой.
- Повторяющееся регеекс ‘a <3>‘ соответствует до трех «А» S за один пробег. Это может сделать это только один раз.
- Повторяющееся регеекс ‘А <1,2>‘ совпадает с одним или двумя «А» s. Он пытается соответствовать как можно больше.
Вы узнали основные кванты регулярных выражений Python.
Альтернативное сообщение об ошибке (фрагменты)
Вы можете столкнуться с любым из следующих фрагментов, которые все приводят к ошибке нескольких повторов:
- Re.Error: множественный повтор в положении
- Многократный повтор в положении
- sre_constants.Error: множественный повтор
- Python Regex Несколько повторов
- Python Re несколько повторять
- Regex Несколько повторов
- Re.error Многократный повтор в положении
Опять же, вы можете исправить ошибку нескольких повторов, избегая укладывающую два кванты Regex друг на друге. Например, рисунок Regex ‘A ++’ приведет к тому, что множественная повторяющаяся ошибка – используйте один квантификатор, такой как ‘A +’ вместо.
Куда пойти отсюда?
Чтобы обобщить, вы узнали, что появится сообщение с несколькими повторениями, когда вы пытаетесь складывать несколько квантов друг на друга. Избегайте этого, и сообщение об ошибке исчезнет.
Если вы хотите повысить навыки Python Regex на следующий уровень, проверьте мое бесплатное угрожающее руководство по нескольким углублению Regeex (20 000+). Или просто заблокировал статью для позже прочитанной.
Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.
Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.
Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.
Источник
Just like me an hour ago, you’re probably sitting in front of your regular expression code, puzzled by a strange error message:
re.error: multiple repeat at position x
Why is it raised? Where does it come from? And, most importantly, how can you get rid of it?
This article gives you answers to all of those questions. Alternatively, you can also watch my short explainer video that shows you real quick how to resolve this error:
Python Regex Multiple Repeat Error
Related article: Python Regex Superpower – The Ultimate Guide
How Does the Multiple Repeat Error Arise in Python Re?
Python’s regex library re
throws the multiple repeat error when you stack two regex quantifiers on top of each other. For example, the regex pattern 'a++'
will cause the multiple repeat error. You can get rid of this error by avoiding to stack quantifiers on top of each other.
Here’s an example:
>>> import re >>> re.findall('a++', 'aaaa') Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> re.findall('a++', 'aaaa') File "C:UsersxcentAppDataLocalProgramsPythonPython37libre.py", line 223, in findall ... re.error: multiple repeat at position 2
I have shortened the error message to focus on the relevant parts. In the code, you first import the regex library re
. You then use the re.findall(pattern, string)
function (see this blog tutorial) to find the pattern 'a++'
in the string 'aaaa'
.
However, this doesn’t make a lot of sense: what’s the meaning of the pattern a++
anyway? Having a single quantifier a+
already reads as “find all matches where at least one character 'a'
matches”.
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
[Tips] What’s the Source of the Multiple Repeat Error and How to Avoid It?
The error happens if you use the Python regex package re
. There are many different reasons but all of them have the same source: you stack quantifiers on top of each other.
If you don’t know what a quantifier is, scroll down and read the following subsection where I show you exactly what it is.
Here’s a list of reasons for the error message. Maybe your reason is among them?
- You use the regex pattern
'X++'
for any regex expressionX
. To avoid this error, get rid of one quantifier. - You use the regex pattern
'X+*'
for any regex expressionX
. To avoid this error, get rid of one quantifier. - You use the regex pattern
'X**'
for any regex expressionX
. To avoid this error, get rid of one quantifier. - You use the regex pattern
'X{m,n}*'
for any regex expressionX
and number of repetitionsm
andn
. To avoid this error, get rid of one quantifier. - You try to match a number of characters
'+'
and use a second quantifier on top of it such as'+?'
. In this case, you should escape the first quantifier symbol'+'
. - You try to match a number of characters
'*'
and use a second quantifier on top of it such as'*+'
. Avoid this error by escaping the first quantifier symbol'*'
.
Oftentimes, the error appears if you don’t properly escape the special quantifier meta-characters in your regex pattern.
Here’s a StackOverflow post that shows some code where this happened:
... term = 'lg incite" OR author:"http++www.dealitem.com" OR "for sale' p = re.compile(term, re.IGNORECASE) ...
I edited the given code snippet to show the important part. The code fails because of a multiple repeat error
. Can you see why?
The reason is that the regex 'lg incite" OR author:"http++www.dealitem.com" OR "for sale'
contains two plus quantifiers stacked on top of each other in the substring 'http++'
. Get rid of those and the code will run again!
Python Regex Quantifiers
The word “quantifier“ originates from latin: it’s meaning is quantus = how much / how often.
This is precisely what a regular expression quantifier means: you tell the regex engine how often you want to match a given pattern.
If you think you don’t define any quantifier, you do it implicitly: no quantifier means to match the regular expression exactly once.
So what are the regex quantifiers in Python?
Quantifier | Meaning |
A? |
Match regular expression A zero or one times |
A* |
Match regular expression A zero or more times |
A+ |
Match regular expression A one or more times |
A{m} |
Match regular expression A exactly m times |
A{m,n} |
Match regular expression A between m and n times (included) |
Note that in this tutorial, I assume you have at least a remote idea of what regular expressions actually are. If you haven’t, no problem, check out my detailed regex tutorial on this blog.
You see in the table that the quantifiers ?
, *
, +
, {m}
, and {m,n}
define how often you repeat the matching of regex A
.
Let’s have a look at some examples—one for each quantifier:
>>> import re >>> re.findall('a?', 'aaaa') ['a', 'a', 'a', 'a', ''] >>> re.findall('a*', 'aaaa') ['aaaa', ''] >>> re.findall('a+', 'aaaa') ['aaaa'] >>> re.findall('a{3}', 'aaaa') ['aaa'] >>> re.findall('a{1,2}', 'aaaa') ['aa', 'aa']
In each line, you try a different quantifier on the same text 'aaaa'
. And, interestingly, each line leads to a different output:
- The zero-or-one regex
'a?'
matches four times one'a'
. Note that it doesn’t match zero characters if it can avoid doing so. - The zero-or-more regex
'a*'
matches once four'a'
s and consumes them. At the end of the string, it can still match the empty string. - The one-or-more regex
'a+'
matches once four'a'
s. In contrast to the previous quantifier, it cannot match an empty string. - The repeating regex
'a{3}'
matches up to three'a'
s in a single run. It can do so only once. - The repeating regex
'a{1,2}'
matches one or two'a'
s. It tries to match as many as possible.
You’ve learned the basic quantifiers of Python regular expressions.
Alternative Error Message (Fragments)
You may encounter any of the following fragments that all lead to the multiple repeat error:
re.error: multiple repeat at position
multiple repeat at position
sre_constants.error: multiple repeat
- python regex multiple repeat
- python re multiple repeat
- regex multiple repeat
re.error multiple repeat at position
Again, you can fix the multiple repeat error by avoiding to stack two regex quantifiers on top of each other. For example, the regex pattern 'a++'
will cause the multiple repeat error—use a single quantifier such as 'a+'
instead.
Where to Go From Here?
To summarize, you’ve learned that the multiple repeat error appears whenever you try to stack multiple quantifiers on top of each other. Avoid this and the error message will disappear.
If you want to boost your Python regex skills to the next level, check out my free in-depth regex superpower tutorial (20,000+) words. Or just bookmark the article for later read.
Regex Humor
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Автор оригинала: Chris.
Также как я час назад, вы, вероятно, сидите перед вашим регулярным кодом выражения, озадачены странным сообщением об ошибке:
re.error: multiple repeat at position x
Почему это подняло? Откуда это взялось? И, самое главное, как вы можете избавиться от этого?
Эта статья дает вам ответы на все эти вопросы. В качестве альтернативы вы также можете посмотреть мое короткое видео об объяснении, которое показывает вам реальный, как разрешить эту ошибку:
Связанная статья: Python Regex SuperPower – Ultimate Guide
Python’s Regex Библиотека Re бросает несколько ошибок повторения, когда вы стекаете два квантализатора Regex друг на друге. Например, рисунок Regex 'A ++'
приведет к нескольким повторной ошибке. Вы можете избавиться от этой ошибки, избегая, чтобы стечь количественными квантами друг на друга.
Вот пример:
>>> import re >>> re.findall('a++', 'aaaa') Traceback (most recent call last): File "", line 1, in re.findall('a++', 'aaaa') File "C:UsersxcentAppDataLocalProgramsPythonPython37libre.py", line 223, in findall ... re.error: multiple repeat at position 2
Я сократил сообщение об ошибке, чтобы сосредоточиться на соответствующих частях. В коде вы впервые импортируете библиотеку Regex Re
Отказ Вы тогда используете Re.findall (шаблон, строка)
Функция ( См. Учебное пособие в блоге ) Чтобы найти шаблон 'A ++'
В строке «АААА»
Отказ
Однако это не имеет большого смысла: в чем смысл шаблона a++
в любом случае? Имея один квантификатор A +
уже читает как «Найти все матчи, где хотя бы один символ 'A'
Матчи» Отказ
Вы хотите освоить сверхдержаву Regeex? Проверьте мою новую книгу Самый умный способ изучать регулярные выражения в Python С инновационным 3-ступенчатым подходом для активного обучения: (1) Изучение книги главы, (2) Решите головоломки кода и (3) Смотреть воспроизведение главы видео.
[Советы] Как источник ошибки нескольких повторов и как его избежать?
Ошибка происходит, если вы используете Python Regex Пакет Re
Отказ Есть много разных причин, но все они имеют одинаковый источник: вы стекаете количественные кванты друг на друга друг на друга.
Если вы не знаете, что такое квантификатор, прокрутите вниз и прочитайте следующий подраздел, где я показываю, что именно то, что оно есть.
Вот список причин для сообщения об ошибке. Может быть, ваша причина в том числе?
- Вы используете шаблон Regex
'X ++'
Для любого выражения RegexX
. Чтобы избежать этой ошибки, избавьтесь от одного квантификатора. - Вы используете шаблон Regex
'Х + *'
Для любого выражения RegexX
. Чтобы избежать этой ошибки, избавьтесь от одного квантификатора. - Вы используете шаблон Regex
'X **'
Для любого выражения RegexX
. Чтобы избежать этой ошибки, избавьтесь от одного квантификатора. - Вы используете шаблон Regex
'X {m, n} *'
Для любого выражения RegexХ
и количество повторенийм
иN
Отказ Чтобы избежать этой ошибки, избавьтесь от одного квантификатора. - Вы пытаетесь сопоставить ряд персонажей
'+'
и используйте второй квантификатор поверх этого, как'+?'
. В этом случае вы должны избежать первого символа квантификатора' +'
Отказ - Вы пытаетесь сопоставить ряд персонажей
'*'
и используйте второй квантификатор поверх этого, как'* +'
Отказ Избегайте этой ошибки, избегая первого символа квантификатора' *'
Отказ
Часто ошибка появляется, если вы не избежите специального квантификатора мета-символов в вашем рисунке Regex.
Вот a Stackoverflow Пост, который показывает какой-то код, где это произошло:
... term = 'lg incite" OR author:"http++www.dealitem.com" OR "for sale' p = re.compile(term, re.IGNORECASE) ...
Я отредактировал данный фрагмент кода, чтобы показать важную роль. Код терпит неудачу из-за Ошибка нескольких повторов
. Вы видите почему?
Причина в том, что регеекс «LG Incite» или автор: «HTTP ++ www.dealitem.com» или "на продажу '
Содержит два плюс количественных квантов, сложенных друг на друга в подстроке 'http ++'
Отказ Избавьтесь от тех, и код снова запустится!
Python Regex Quebifiers
Слово “ квантификатор “ Возникает из латыни: это значение Кванс много/Как часто Отказ
Это именно то, что означает регулярное определение количества выражений: вы сообщите двигателю REGEX, как часто вы хотите сопоставить данный шаблон.
Если вы считаете, что вы не определяете какой-либо квантификатор, вы делаете это неявно: никакого количества означает совпадение регулярного выражения ровно.
Так Каковы квантования Regeex в Python?
Квантификатор | Имея в виду |
А? | Сопоставить регулярное выражение ноль или один раз |
A* | Сопоставить регулярное выражение нуля или более раз |
A+ | Сопоставить регулярное выражение единое или несколько раз |
Являюсь} | Соответствовать регулярному выражению точно M раз |
A {m, n} | Соответствовать регулярному выражению между m и n раз (включая) |
Обратите внимание, что в этом руководстве я предполагаю, что у вас есть хотя бы удаленное представление о том, какие регулярные выражения на самом деле являются. Если у вас нет проблем, не ознакомьтесь с моим подробным руководством REGEX в этом блоге.
Вы видите в таблице, что квантаторы ?
, *
, +
, {м}
и {m, n}
Определите, как часто вы повторяете сопоставление Regex A
.
Давайте посмотрим на некоторые примеры – один для каждого квантификатора:
>>> import re >>> re.findall('a?', 'aaaa') ['a', 'a', 'a', 'a', ''] >>> re.findall('a*', 'aaaa') ['aaaa', ''] >>> re.findall('a+', 'aaaa') ['aaaa'] >>> re.findall('a{3}', 'aaaa') ['aaa'] >>> re.findall('a{1,2}', 'aaaa') ['aa', 'aa']
В каждой строке вы попробуйте другой квантификатор на одном тексте «АААА»
Отказ И, интересно, каждая строка приводит к другому выходу:
- нулевой или один Regex
'а?
соответствует четыре раза один«А»
Отказ Обратите внимание, что он не соответствует нулевым символам, если он может избежать этого. - ноль или-другое Regex
« A * '
совпадает раз в четырех«А»
и поглощает их. В конце строки он все еще может сравниться с пустой строкой. - одно- или больше Regex
'A +'
совпадает раз в четырех«А»
s. В отличие от предыдущего квантификатора, он не может сравниться с пустой строкой. - Повторяющееся регеекс
'a {3}'
соответствует до трех«А»
S за один пробег. Это может сделать это только один раз. - Повторяющееся регеекс
'А {1,2}'
совпадает с одним или двумя«А»
s. Он пытается соответствовать как можно больше.
Вы узнали основные кванты регулярных выражений Python.
Альтернативное сообщение об ошибке (фрагменты)
Вы можете столкнуться с любым из следующих фрагментов, которые все приводят к ошибке нескольких повторов:
Re.Error: множественный повтор в положении
Многократный повтор в положении
sre_constants.Error: множественный повтор
- Python Regex Несколько повторов
- Python Re несколько повторять
- Regex Несколько повторов
Re.error Многократный повтор в положении
Опять же, вы можете исправить ошибку нескольких повторов, избегая укладывающую два кванты Regex друг на друге. Например, рисунок Regex 'A ++'
приведет к тому, что множественная повторяющаяся ошибка – используйте один квантификатор, такой как 'A +'
вместо.
Куда пойти отсюда?
Чтобы обобщить, вы узнали, что появится сообщение с несколькими повторениями, когда вы пытаетесь складывать несколько квантов друг на друга. Избегайте этого, и сообщение об ошибке исчезнет.
Если вы хотите повысить навыки Python Regex на следующий уровень, проверьте мое бесплатное угрожающее руководство по нескольким углублению Regeex (20 000+). Или просто заблокировал статью для позже прочитанной.
Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.
Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.
Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.
Оригинал: “https://blog.finxter.com/python-regex-multiple-repeat-error/”
Я использую регулярное выражение для замены любой строки, которая появляется после слова username, за которым следует (:
или ;)
, с дополнительными пробелами с одним необязательным пробелом между ними.
Я использую следующее регулярное выражение в PHP:
(?i)bUsernames?+(:|;)s?+KS+
Однако я хотел знать, как использовать то же выражение в python, когда я получаю сообщение об ошибке: error: multiple repeat at position 17"
.
Ниже приведен мой тестовый пример, и я хотел извлечь только dasdsad
из всех примеров.
Есть ли способы достичь этого в Python?
Username:dasdsad
username ;dasdsad
username : dasdsad
username; dasdsad
2 ответа
Лучший ответ
Использование
(?i)bUsernames*[:;]s*(S+)
См. доказательство. Вместо K
используйте группу захвата, (S+)
захватит один или несколько непробельных символов в группу.
демонстрационный код Python:
import re
regex = r"(?i)bUsernames*[:;]s*(S+)"
test_str = ("Username:dasdsadn"
"username ;dasdsadn"
"username : dasdsadn"
"username; dasdsad")
print( re.findall(regex, test_str) )
< Сильный > UPDATE :
Чтобы заменить и сохранить часть использования матча
test_str = re.sub(r'(?i)(bUsernames*[:;]s*)S+', r'1username', test_str)
Если вам нужно заменить цифрой:
test_str = re.sub(r'(?i)(bUsernames*[:;]s*)S+', r'g<1>1234', test_str)
0
Ryszard Czech
18 Июн 2020 в 20:34
Python не поддерживает собственнические квантификаторы или K
.
Если вы хотите заменить спички, вам не нужно s?+
.
Вы можете использовать s*
и использовать K
, а также использовать модуль regex pypi и использовать regex.sub
bUsernames*[:;]s*KS+
Regex demo | Python демо
import regex
pattern = r"(?i)bUsernames*[:;]s*KS+"
test_str = ("Username:dasdsadn"
"username ;dasdsadn"
"username : dasdsadn"
"username; dasdsad")
print(regex.sub(pattern, "REPLACEMENT", test_str))
Выход
Username:REPLACEMENT
username ;REPLACEMENT
username : REPLACEMENT
username; REPLACEMENT
1
The fourth bird
18 Июн 2020 в 20:33
Thread Rating:
- 0 Vote(s) — 0 Average
- 1
- 2
- 3
- 4
- 5
Regular expressions help re.error: multiple repeat at position 23 |
This is a menu for someone to de-codify a food menu and know what the client has asked for. The issue is that it only gives back the answer correctly to the code: «RES71PQ». If I introduce the other testings I have to do, which are «RED4», «QEGRVN» and «TCAGR» it gives a big message but I don’t understand it. Help! This is a really important homework. Thanks import re def sabor1(pedido): if pedido[2]=="S": return "salado" else: return "dulce" def sabor2(pedido): if pedido[5]=="N": return "Vainilla" elif pedido[5]=="R": return "Fresa-chocolate" elif pedido[5]=="M": return "Caramelo" else: return "Chocolate" def articulo(pedido): if pedido[3]==1 or pedido[3]==2 or pedido[3]==4 or pedido[3]==5: return "un" else: return "una" def tamano(pedido): if pedido[4]=="P"or pedido[5]=="P": return "de tamaño pequeño" elif pedido[4]=="M"or pedido[5]=="M": return "de tamaño mediano" else: return "de tamaño grande" def tamano2(pedido): if pedido[2]=="P": return "de tamaño: pequeño" else: return "de tamaño: grande" def comida(pedido): if int(pedido[3])==1: return "Nidito" elif int(pedido[3])==2: return "Palito de queso" elif int(pedido[3])==3: return "Orejita" elif int(pedido[3])==4: return "Biscuit" elif int(pedido[3])==5: return "Crocante" elif int(pedido[3])==6: return "Enchilada" elif int(pedido[3])==7: return "Empanada" def verificarPedidos(pedido): """ Funcionaliad: Verifica el código que ingresó el usuario y devuelve el producto Entrada: Un código alfanumérico Salida: El producto correspondiente al código anterior """ if re.match ("^RE[D|S]{1}[1-6]{1}[PQ|MD|GD]*$",pedido): print ("Usted solicita una repostería de sabor "+sabor1(str(pedido))+", correspondiente a "+articulo(str(pedido))+" :"+comida(str(pedido))+","+tamano(str(pedido))) elif re.match ("^RE[D|S]{1}[1-6]{1}$",pedido): print ("Usted solicita una repostería de sabor "+sabor1(str(pedido))+", correspondiente a "+articulo(str(pedido))+" :"+comida(str(pedido))+".") elif re.match ("^RE[D|S]{1}7{1}[1|2]{1}[PQ|MD|GD]*$",pedido): print ("Usted solicita una repostería de sabor "+sabor1(str(pedido))+", correspondiente a "+articulo(str(pedido))+" : Empanada, "+tamano(str(pedido))) elif re.match ("^RE[D|S]{1}7{1}[1|2]{1}*$",pedido): print ("Usted solicita una repostería de sabor "+sabor1(str(pedido))+", correspondiente a "+articulo(str(pedido))+" : Empanada, ") elif re.match ("^QE{1}[GR|PQ]{1}[VN|FR|CM|CE]{1}$",pedido): print ("Usted solicita un queque de sabor de "+sabor2(str(pedido))+", "+tamano2(str(pedido))) elif re.match ("^TCAGR{1}$",pedido): print ("Usted solicita una torta chilena, de tamaño: grande. ") #Menu def opcionverificarPedidos(): """ Funcionalidad: Validar y reconocer cual producto se desea Entrada: Código Salida: Qué es lo que el cliente pide """ print ("n------------------------n") print ("Según el menú mostrado anteriormente, eliga su pedido según corresponda el código de la comida con su pedido") print ("n------------------------n") pedido= input("Ingrese un código de comida: ") print ("") print ("") print (verificarPedidos(pedido)) print ("") print ("") def menuSpoon(): print ("n**************************n") print ("≣≣≣≣≣≣≣≣ Menú Spoon™ ≣≣≣≣≣≣≣≣≣") print ("n"*1) print ("Bienvenido al menú decodificador. Esperamos tenga una experiencia agradable. ") print ("n**************************n") print ("Los productos disponibles son:") print ("1. Repostería:") print ("2. Queques:") print ("3. Tortas Chilenas grandes ") print ("") pedido=(input("Escoja un alimento y digite su código: ")) if pedido!="": print(verificarPedidos(pedido)) print("") print("") else: print ("El código ingresado no coincide con el inventario actual de productos Spoon™. Inténtelo nuevamente tomando en cuenta el orden en el que ingresa los datos. ") continuar=input("Desea decodificar un nuevo producto? ") if continuar=="Si" or continuar=="SI" or continuar=="sí" or continuar=="SÍ" or continuar=="si" or continuar=="Sí": print("") print("") menuSpoon() else: return menuSpoon()
This is a really important homework pls help! Posts: 4,229 Threads: 97 Joined: Sep 2016 Reputation: We need the big message you’re getting. All of it. Exactly. And is that the actual indentation of your file? Because if it is, that’s your problem. Posts: 566 Threads: 10 Joined: Apr 2017 Reputation: If they did not teach to name variables in English… Variable names are part of function documentation, helping your reader to understand the code. Portuguese — you are discouraging your potential helpers from the international community. Also, your code is too crowded, make it still less readable — see PEP-8 for guidance. And don’t show the full code — show just places that don’t work (again, helps your potential helpers to concentrate on your problem — and not on long strings most won’t be able to read) Still:
Couple of generic pointers:
Test everything in a Python shell (iPython, Azure Notebook, etc.)
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Repeat request by else | stsxbel | 2 | 570 |
Jul-30-2022, 03:34 PM Last Post: stsxbel |
|
How to move multiple columns to initial position | SriRajesh | 4 | 661 |
Jul-02-2022, 10:34 AM Last Post: deanhystad |
|
List Creation and Position of Continue Statement In Regular Expression Code | new_coder_231013 | 3 | 869 |
Jun-15-2022, 12:00 PM Last Post: new_coder_231013 |
|
get out of while loop and stop repeat | Frankduc | 11 | 1,403 |
Apr-26-2022, 10:09 PM Last Post: deanhystad |
|
Avoid multiple repeat in indent | Frankduc | 8 | 1,811 |
Jan-18-2022, 05:46 PM Last Post: Frankduc |
|
python error: bad character range |-t at position 12 | faustineaiden | 0 | 2,485 |
May-28-2021, 09:38 AM Last Post: faustineaiden |
|
Having trouble with regular expressions | mikla | 3 | 1,810 |
Mar-16-2021, 03:44 PM Last Post: bowlofred |
|
Statements and Expressions | Julie | 1 | 1,151 |
Feb-26-2021, 05:19 PM Last Post: nilamo |
|
How to discard list repeat values | akanowhere | 7 | 2,544 |
Dec-28-2020, 09:14 PM Last Post: akanowhere |
|
I want to check if the input is str or is int & if it’s str repeat the loop | HLD202 | 4 | 1,917 |
Nov-23-2020, 11:01 PM Last Post: perfringo |
Created on 2016-08-19 12:07 by martin.panter, last changed 2022-04-11 14:58 by admin. This issue is now closed.
Files | |||
---|---|---|---|
File name | Uploaded | Description | Edit |
multiple-repeat.patch |
martin.panter, 2016-09-04 06:50 |
review |
Messages (9) | ||
---|---|---|
msg273107 — (view) | Author: Martin Panter (martin.panter) * |
Date: 2016-08-19 12:06 |
In the documentation for the “re” module, it says repetition codes like {4} and “*” operate on the preceding regular expression. But even though “a{4}” is a valid expression, the obvious way to apply a “*” repetition to it fails: >>> re.compile("a{4}*") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/proj/python/cpython/Lib/re.py", line 223, in compile return _compile(pattern, flags) File "/home/proj/python/cpython/Lib/re.py", line 292, in _compile p = sre_compile.compile(pattern, flags) File "/home/proj/python/cpython/Lib/sre_compile.py", line 555, in compile p = sre_parse.parse(p, flags) File "/home/proj/python/cpython/Lib/sre_parse.py", line 792, in parse p = _parse_sub(source, pattern, 0) File "/home/proj/python/cpython/Lib/sre_parse.py", line 406, in _parse_sub itemsappend(_parse(source, state)) File "/home/proj/python/cpython/Lib/sre_parse.py", line 610, in _parse source.tell() - here + len(this)) sre_constants.error: multiple repeat at position 4 As a workaround, I found I can wrap the inner repetition in (?:. . .): >>> re.compile("(?:a{4})*") re.compile('(?:a{4})*') The problems with the workaround are (a) it is far from obvious, and (b) it adds more complicated syntax. Either this limitation should be documented, or if there is no good reason for it, it should be lifted. It is not clear if my workaround is entirely valid, or if I just found a way to bypass some sanity check. My original use case was scanning a base-64 encoding for Issue 27799: # Without the second level of brackets, this raises a "multiple repeat" error chunk_re = br'(?: (?: [^A-Za-z0-9+/=]* [A-Za-z0-9+/=] ){4} )*' |
||
msg273133 — (view) | Author: R. David Murray (r.david.murray) * |
Date: 2016-08-19 15:03 |
It seems perfectly logical and consistent to me. {4} is a repeat count, as is *. You get the same error if you do 'a?*', and the same bypass if you do '(a?)*' (though I haven't tested if that does anything useful :). You don't need the ?:, as far as I can tell, you just need to have the * modifying a group, making the group the "preceding regular expression". |
||
msg273147 — (view) | Author: Matthew Barnett (mrabarnett) * |
Date: 2016-08-19 17:34 |
"*" and the other quantifiers ("+", "?" and "{...}") operate on the preceding _item_, not the entire preceding expression. For example, "ab*" means "a" followed by zero or more repeats of "b". You're not allowed to use multiple quantifiers together. The proper way is to use the non-capturing "(?:...)". It's too late to change that because some of them already have a special meaning when used after another quantifier: "a*?" is a lazy quantifier, as are "a+?", "a??" and "a{1,4}?". Many other regex implementations, including the "regex" module, use an additional "+" to signify a possessive quantifier: "a*+", "a++", "a?+" and "a{1,4}+". That just leaves the additional "*", which is treated as an error in all the other regex implementations that I'm aware of. |
||
msg273148 — (view) | Author: Terry J. Reedy (terry.reedy) * |
Date: 2016-08-19 17:44 |
This appears to be a doc issue to clarify that * cannot directly follow a repetition code. I believe there have been other (non)bug reports like this before. |
||
msg273178 — (view) | Author: Martin Panter (martin.panter) * |
Date: 2016-08-20 01:18 |
Okay so it sounds like my usage is valid if I add the brackets. I will try to come up with a documentation patch as some stage. The reason why it is not supported without brackets is to maintain a bit of consistency with the question mark (?), which modifies the preceding quantifier, and with the plus sign (+), which is also a modifier in other implementations. For the record, Gnu grep does seem to accept my expression (although Posix says this is undefined, and neither support lazy or possessive quantifiers): $ grep -E -o 'a{2}*' <<< "aaaaa" aaaa However pcregrep, which supports lazy (?) and possessive (+) quantifiers, doesn’t like my expression: $ pcregrep -o 'a{2}*' <<< "aaaaa" pcregrep: Error in command-line regex at offset 4: nothing to repeat [Exit 2] $ pcregrep -o '(?:a{2})*' <<< "aaaaa" aaaa |
||
msg274344 — (view) | Author: Martin Panter (martin.panter) * |
Date: 2016-09-04 06:50 |
Here is a patch for the documentation. |
||
msg274347 — (view) | Author: Serhiy Storchaka (serhiy.storchaka) * |
Date: 2016-09-04 07:20 |
LGTM. Thanks Martin. |
||
msg278682 — (view) | Author: Roundup Robot (python-dev) |
Date: 2016-10-15 01:45 |
New changeset 5f7d7e079e39 by Martin Panter in branch '3.5': Issue #27800: Document limitation and workaround for multiple RE repetitions https://hg.python.org/cpython/rev/5f7d7e079e39 New changeset 1f2ca7e4b64e by Martin Panter in branch '3.6': Issue #27800: Merge RE repetition doc from 3.5 into 3.6 https://hg.python.org/cpython/rev/1f2ca7e4b64e New changeset 98456ab88ab0 by Martin Panter in branch 'default': Issue #27800: Merge RE repetition doc from 3.6 https://hg.python.org/cpython/rev/98456ab88ab0 New changeset 94f02193f00f by Martin Panter in branch '2.7': Issue #27800: Document limitation and workaround for multiple RE repetitions https://hg.python.org/cpython/rev/94f02193f00f |
||
msg278690 — (view) | Author: Martin Panter (martin.panter) * |
Date: 2016-10-15 03:24 |
I committed my patch as it was. I understand Silent Ghost’s objection was mainly that they thought the new paragraph or its positioning wouldn’t be very useful, but hopefully it is better than nothing. Perhaps in the future, the documentation could be restructured with subsections for repetition qualifiers and other kinds of special codes, which may help. |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:58:35 | admin | set | github: 71987 |
2016-10-15 03:24:45 | martin.panter | set | status: open -> closed resolution: fixed messages: + msg278690 stage: commit review -> resolved |
2016-10-15 01:45:34 | python-dev | set | nosy: + python-dev messages: + msg278682 |
2016-10-01 14:57:11 | serhiy.storchaka | set | assignee: martin.panter stage: patch review -> commit review versions: + Python 3.7 |
2016-09-04 07:20:17 | serhiy.storchaka | set | nosy: + serhiy.storchaka messages: + msg274347 |
2016-09-04 06:50:36 | martin.panter | set | files: + multiple-repeat.patch keywords: + patch messages: + msg274344 stage: patch review |
2016-08-20 01:18:28 | martin.panter | set | messages: + msg273178 |
2016-08-19 17:44:56 | terry.reedy | set | nosy: + terry.reedy messages: + msg273148 |
2016-08-19 17:34:56 | mrabarnett | set | messages: + msg273147 |
2016-08-19 15:03:59 | r.david.murray | set | nosy: + r.david.murray messages: + msg273133 |
2016-08-19 12:07:00 | martin.panter | create |
Multiple repeat error when the regex has multiple wildcards in python re module
When the regex being compiled in python which has multiple wild cards like plus or asterisks sequentially repeated, you will need to escape or else run into «multiple repeat error». This can happen with any of re module methods like search and sub etc, where the regex is compiled.
>>> import re >>> re.compile("r++") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 242, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat >>> re.compile("r**") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 242, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat
To avoid the miscellaneous like this we just need to escape the string with if we need to do the exact match without any wildcard expansions.
>>> re.compile(re.escape('r++')) <_sre.SRE_Pattern object at 0xb74e28a0>
Popular posts from this blog
Understanding multiple inheritance and method resolution order in Python
# cat multiple_inheritance.py import inspect class A ( object ): pass class B (A): pass class C (A): pass class D (B): pass class E (C): pass class F (D, E): pass print inspect.getmro(A) print inspect.getmro(B) print inspect.getmro(C) print inspect.getmro(D) print inspect.getmro(E) print inspect.getmro(F) # python multiple_inheritance.py (< class ‘ __main__ .A ‘>, <type ‘ object ‘>) (< class ‘ __main__ .B ‘>, <class ‘ __main__.A ‘>, <type ‘ object ‘>) (< class ‘ __main__ .C ‘>, <class ‘ __main__.A ‘>, <type ‘ object ‘>) (< class ‘ __main__ .D ‘>, <class ‘ __main__.B ‘>, <class ‘ __main__.A ‘>, <type ‘ object ‘>) (< class ‘ __main__ .E ‘>, <class ‘ __main__.C ‘>, <class ‘ __main__.A ‘>, <type ‘ object ‘>) (< class ‘
To speed up accessing files on nfs shares on a ubuntu machine …
To enable nfs caching on ubuntu, sudo apt-get install cachefilesd sudo sed -i ‘s/nfs rw/nfs fsc,rw/’ /etc/fstab service restart cachefilesd To use tmpfs instead of disk cache use this after making sure the runner has atleast 12G of memory, mount | grep fscache || mount -t tmpfs -o size=8192m tmpfs /fscache ls /fscache/disk0 || dd if=/dev/zero of=/fscache/disk0 bs=1M count=8191 sleep 15 ls /fscache/disk0 && echo ‘y’ | mkfs.ext4 /fscache/disk0 mount /fscache/disk0 /var/cache/fscache -t ext4 service cachefilesd restart