如何修复错误的转义正则表达式错误 (python re)

How to fix bad escape regex error (python re)

我一直在研究 re.sub() 以了解如何将格式从 Y-m-d 更改为 M/d/y。为了执行测试,我定义了起始变量:current_date = "2012-05-26"

我会尝试将该日期转换为 05/26/2012。

我试图在不使用 DateTime 的情况下使用正则表达式来实现这一点。我使用 re.sub 如下:

formatted_date = re.sub(r"\d{2,4}-\d{1,2}-\d{1,2}", r"[^a-zA-Z]\d{1,2}/\d{1,2}/\d{2,4}", current_date)

第一个正则表达式匹配Y-M-D的原始格式,第二个正则表达式尝试将其转换为我想要的格式。我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\ghub4\AppData\Local\Programs\Python\Python39\lib\sre_parse.py", line 1039, in parse_template
    this = chr(ESCAPES[this][1])
KeyError: '\d'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\ghub4\OneDrive\Desktop\test_sub.py", line 5, in <module>
    formatted_date = re.sub(r"\d{2,4}-\d{1,2}-\d{1,2}", r"[^a-zA-Z]\d{1,2}/\d{1,2}/\d{2,4}", current_date)
  File "C:\Users\ghub4\AppData\Local\Programs\Python\Python39\lib\re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "C:\Users\ghub4\AppData\Local\Programs\Python\Python39\lib\re.py", line 327, in _subx
    template = _compile_repl(template, pattern)
  File "C:\Users\ghub4\AppData\Local\Programs\Python\Python39\lib\re.py", line 318, in _compile_repl
    return sre_parse.parse_template(repl, pattern)
  File "C:\Users\ghub4\AppData\Local\Programs\Python\Python39\lib\sre_parse.py", line 1042, in parse_template
    raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \d at position 9

完整代码:

import re

current_date = "2012-05-26"

formatted_date = re.sub(r"\d{2,4}-\d{1,2}-\d{1,2}", r"[^a-zA-Z]\d{1,2}/\d{1,2}/\d{2,4}", current_date)

print(formatted_date)

我已将错误追溯到潜在的第二个正则表达式,但我不确定位置 9 在哪里以及如何修复错误。我不确定如何修复它的另一个原因是第一个错误指出 \d 引发的键盘错误。我确定当正则表达式在代码中的某处被解释时,它会将 \d 视为 \d 而不是我也不确定如何防止这种情况发生。我也很确定第二个正则表达式可能会适得其反,并且在发布此问题后我正在研究解决方案。我怎样才能纠正这些错误?

正则表达式的替换字符串本身不是正则表达式,而是一个可能包含对原始正则表达式捕获的组的引用的字符串。在您的例子中,您想要捕获年、月和日,然后将它们输出到结果字符串中。您可以在要捕获的值周围使用 () 来执行此操作,然后在替换字符串中通过 </code>、<code></code> 引用组,并使用数字按照被捕获的组的顺序分配。因此,对于您的代码,您需要:</p> <pre><code>formatted_date = re.sub(r"(\d{2,4})-(\d{1,2})-(\d{1,2})", r"//", current_date)

尝试对您的数字进行分组(如果您的目标是测试,那么位置 9 是您在第二次正则表达式检查中的第一个 \d - 这是一个无效的组引用):

formatted_date = re.sub(r"(\d{2,4})-(\d{1,2})-(\d{1,2})",r"//",current_date)