簡體   English   中英

如何在python中使用正則表達式用正則表達式模式替換子字符串?

[英]How to replace a substring with a regex pattern using regex in python?

我有一個字符串"word ***.** word" 我想用'[\\d][\\d][\\d].[\\d]+'替換'***.**' '[\\d][\\d][\\d].[\\d]+' 無法使用正則表達式執行此操作,因為它為'\\d'提供了關鍵錯誤。 我的代碼是:

text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\b\*\*\*\b', re.I), '[\d][\d][\d]', text)

我收到此錯誤:

Traceback (most recent call last):
  File "/usr/lib/python3.8/sre_parse.py", line 1039, in parse_template
this = chr(ESCAPES[this][1])
KeyError: '\\d'

我知道我的代碼不正確。 但我想不出任何不同的方式。 在社區博客中也沒有找到任何內容。

這應該可以解決問題:

import re

text = 'word ***.** word'
updated_text = re.sub(re.compile(r'\*', re.I), r'[\\d]', text)
print(updated_text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM