小编Son*_*ars的帖子

使用python正则表达式转义无效降价

我一直在尝试编写一些 python 来转义“无效”降价字符串。

这是用于需要使用 \ 转义未使用的降价字符的 python 库 (python-telegram-bot)。

我的目标是匹配单独的*, _,`字符以及无效的超链接 - 例如,如果没有提供链接,并转义它们。

我正在寻找的一个例子是:

*hello*很好,不应该改变,而hello*会变成hello\*. 最重要的是,如果值是嵌套的,它们不应该被转义——例如_hello*_应该保持不变。

我的想法是先匹配所有双打,然后替换任何剩余的孤独字符。我使用 re.finditer() 管理了一个粗略的版本:

 def parser(txt):
   match_md = r'(\*)(.+?)(\*)|(\_)(.+?)(\_)|(`)(.+?)(`)|(\[.+?\])(\(.+?\))|(?P<astx>\*)|(?P<bctck>`)|(?P<undes>_)|(?P<sqbrkt>\[)'
   for e in re.finditer(match_md, txt):
     if e.group('astx') or e.group('bctck') or e.group('undes') or e.group('sqbrkt'):
       txt = txt[:e.start()] + '\\' + txt[e.start():]
   return txt

note: regex was written to match *text*, _text_, `text`, [text](url), and then single *, _, `, [, knowing the last groups
Run Code Online (Sandbox Code Playgroud)

但这里的问题当然是当您插入更多字符时偏移量会发生变化,因此一切都会发生变化。肯定有比添加偏移计数器更好的方法吗? …

regex string markdown replace python-3.x

5
推荐指数
1
解决办法
1918
查看次数

标签 统计

markdown ×1

python-3.x ×1

regex ×1

replace ×1

string ×1