我试图在python中模仿来自GitHub的击穿标记,我设法完成了一半的工作。现在我只有一个问题:我正在使用的模式似乎没有替换包含符号的文本,我无法弄明白所以我希望有人可以帮助我
text = "This is a ~~test?~~"
match = re.findall(r"(?<![.+?])(~{2})(?!~~)(.+?)(?<!~~)\1(?![.+?])", text) # Finds all the text between ~~ symbols
if match:
for _, m in match: # Iterates though the matches. First variable (_) containing the symbol ~ and the second one (m) contains the text I want to replace
text = re.sub(f"~~{m}~~", "\u0336".join(m) + "\u0336", text) # Should replace ~~test?~~ with t̶e̶s̶t̶?̶ but it fails
您要替换的字符串中存在问题。在你的情况下,~~{m}~~
,其中m
的值是test?
,要替换的正则表达式变成~~test?~~
,这里?
有一个特殊的含义,你没有逃避,因此替换不能正常工作。只是尝试使用re.escape(m)
而不是m
,因此元字符被转义并被视为文字。
试试你修改过的Python代码,
import re
text = "This is a ~~test?~~"
match = re.findall(r"(?<![.+?])(~{2})(?!~~)(.+?)(?<!~~)\1(?![.+?])", text) # Finds all the text between ~~ symbols
if match:
for _, m in match: # Iterates though the matches. First variable (_) containing the symbol ~ and the second one (m) contains the text I want to replace
print(m)
text = re.sub(f"~~{re.escape(m)}~~", "\u0336".join(m) + "\u0336", text) # Should replace ~~test?~~ with t̶e̶s̶t̶?̶ but it fails
print(text)
这取代了你想象和打印,
This is a t̶e̶s̶t̶?̶