簡體   English   中英

尋找正則表達式來轉義特殊字符集

[英]Looking for regular expression to escape special set of characters

目標是用\\_\\*分別替換在 Markdown 中具有特殊作用的字符串中的字符,例如_*

我當前的方法如下所示:

text = "Text *here* should be _formatted_"
specials = ["*", "_"]
for char in specials:
    text = text.replace(char, f"\\{char}")

想知道是否有其他方法可以使用正則表達式實現此功能。

可以在 re.sub() function 中使用它來轉義特殊字符
還沒有逃脫。

r"(?<?\\)((::\\\\)*)([*_])"

https://regex101.com/r/8LNp5E/1

示例 Python

>>> import re
>>> target = (
...    r"The goal is to replace characters in string such as _ and * in that have" + "\n"
...    r"special role in Markdown \\_ and \\*  and  \_ and \* ." + "\n"
...   )
>>>
>>> res = re.sub( r"(?<!\\)((?:\\\\)*)([*_])", r"\1\\\2", target )
>>>
>>> print ( res )
The goal is to replace characters in string such as \_ and \* in that have
special role in Markdown \\\_ and \\\*  and  \_ and \* .

暫無
暫無

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

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