简体   繁体   English

寻找正则表达式来转义特殊字符集

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

The goal is to replace characters in string such as _ and * that have special role in Markdown with \\_ and \\* respectively.目标是用\\_\\*分别替换在 Markdown 中具有特殊作用的字符串中的字符,例如_*

My current method looks like this:我当前的方法如下所示:

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

Wondering if there is alternative way of achieving this functionality with regular expressions.想知道是否有其他方法可以使用正则表达式实现此功能。

Its possible to use this in a re.sub() function to escape special characters可以在 re.sub() function 中使用它来转义特殊字符
that aren't already escaped.还没有逃脱。

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

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

Example Python示例 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