【问题标题】:appending string with integer values python re用整数值附加字符串python re
【发布时间】:2017-05-28 11:55:32
【问题描述】:

我试图在 python 中使用正则表达式将日期插入字符串

link = 'branch=;deps=;date=;rev=;days=1;user='
date = "10.12.2016"
re.sub(r'(.*)(date=[^;]*)(.*)','\\1\\2'+date+'\\3',link)

我期待输出是

'branch=;deps=;date=10.12.2016;rev=;days=1;user='

但我得到了这个,

'branch=;deps=;**\x88.12.2016**;rev=;days=1;user='

另一件事,如果我在日期变量中有一些字符串,它可以替换就好了。

date="hello"
re.sub(r'(.*)(date=[^;]*)(.*)','\\1\\2'+date+'\\3',link)

给予,

'branch=;deps=;**date=hello**;rev=;days=1;user='

这可能是什么问题?

【问题讨论】:

    标签: python regex python-2.7 text-processing


    【解决方案1】:

    为什么要让它变得困难?跳过re

    >>> link = 'branch=;deps=;date=;rev=;days=1;user='
    >>> date = "10.12.2016"
    >>> link = link.replace('date=','date='+date)
    >>> link
    'branch=;deps=;date=10.12.2016;rev=;days=1;user='
    

    或者用re,但基本一样:

    >>> re.sub(r'date=','date='+date,link)
    'branch=;deps=;date=10.12.2016;rev=;days=1;user='
    

    脚本中的错误为 '\\1\\2'+date+'\\3',计算结果为 '\\1\\210.12.2016\\3''\\210' 评估为八进制转义,相当于'\x88'。你可以通过使用\g<n> 序列来解决这个问题:

    >>> re.sub(r'(.*)(date=[^;]*)(.*)','\\1\\g<2>'+date+'\\3',link)
    'branch=;deps=;date=10.12.2016;rev=;days=1;user='
    

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 2021-03-12
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多