python - 错误 : nothing to repeat at position 0 using regex in python

标签 python regex

给定一个截尾字符串和一个截尾元音字符串,返回 未经审查的原始字符串。

import re

def uncensor(string1, string2):
  # Use a regular expression to find all the asterisks in string1
  asterisks = re.findall(r'\*?', string1)

  # Replace each asterisk with the corresponding character from string2
  for i, asterisk in enumerate(asterisks):
    string1 = re.sub(asterisk, string2[i], string1, count=1)

  return string1

uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") #➞ "Where did my vowels go?"

我收到以下错误:

error                                     Traceback (most recent call last)
<ipython-input-28-fee597a500f6> in <module>
     11   return string1
     12 
---> 13 uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") #➞ "Where did my vowels go?"

6 frames
/usr/lib/python3.8/sre_parse.py in _parse(source, state, verbose, nested, first)
    666                 item = None
    667             if not item or item[0][0] is AT:
--> 668                 raise source.error("nothing to repeat",
    669                                    source.tell() - here + len(this))
    670             if item[0][0] in _REPEATCODES:

error: nothing to repeat at position 0

我尝试了模式 r'*+*' 、 r'*' 、 r'*+' 但我总是出错。

我在期待这个

uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo") ➞ “我的元音去哪儿了?”

最佳答案

您当前的方法存在多个问题,包括函数逻辑和正则表达式的使用。我会通过使用回调函数对 \* 进行正则表达式替换来解决这个问题。在回调中,对于每次出现的 *,我们可以从替换元音列表中弹出一个元音。

import re

def uncensor(string1, string2):
    chars = list(string2)
    return re.sub(r'\*', lambda m: chars.pop(0), string1)

output = uncensor("Wh*r* d*d my v*w*ls g*", "eeioeo")
print(output)  # Where did my vowels go

关于python - 错误 : nothing to repeat at position 0 using regex in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74760720/

相关文章:

Python 按日期范围求和值

regex - 如何匹配任一/或正则表达式

regex - 如何设置不匹配的REGEX?

基于 Python 文本的游戏房间到房间的移动

python - 使用数据框在 Databricks 上进行 Pandas 分析时出错

python - 解析时出现意外的 EOF

Python3 将所有字符转换为 HTML 实体

java - 在 Talend 5.5 中使用正则表达式的 jsonpath

Javascript 正则表达式替换并添加找到的所有元素到数组

php - 匹配字符集和可选实体