【问题标题】:(Python 2.7) Regex Replace with similar character in replacement string as in pattern [duplicate](Python 2.7)正则表达式替换为替换字符串中与模式中相似的字符[重复]
【发布时间】:2020-04-12 04:16:15
【问题描述】:
import re
pattern = re.compile(r"/")
a = "a/b"

我试过了

re.sub(pattern, '\/', a) 
#(also, a.replace('/', '\/'))
#output
a\\/b

我想要的是

a\/b

【问题讨论】:

  • 听起来像你想要的a.replace('/','\\/')
  • 尝试:x=re.sub(pattern, '\/', a) 然后print(x)。已经对了
  • 您的代码正在运行 - rextester.com/NNB40155
  • @GrzegorzSkibinski 我有 python 2.7,但它不工作。也许它会在 3.x 中工作。
  • 是的,如果你打印结果,你会得到a\/b,但不知道为什么你使用re.sub而不是pattern.sub('\/', a)

标签: python regex python-2.7


【解决方案1】:
a.replace('/', '\\/')

第一个\是一个转义字符,所以你需要输入两次才能得到真正的\

【讨论】:

  • 你用的是什么版本的python?
  • 我使用的是 Python 3.7,但它也适用于 2.7
  • 是的,你是对的。其实我是在 jupyter 中运行的,没有 print() 语句,否则没问题。
【解决方案2】:

如果不是强制使用正则表达式,您可以使用:

a = "a/b"
a=a.replace("/","\/")
print(a)

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2012-04-26
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多