【问题标题】:Python replace using regexPython 使用正则表达式替换
【发布时间】:2012-02-08 11:27:33
【问题描述】:

有谁知道如何用 '\r\n

"<20"

应该转化为

"\r\n<20"

但是

"> HELLO < asassdsa"

应该保持不变

【问题讨论】:

    标签: python regex


    【解决方案1】:
    >>> import re
    >>> str = "<20"
    >>> output = re.sub(r'<(?=\d)', r'\r\n<', str)
    >>> output
    '\r\n<20'
    

    【讨论】:

    • 为什么不一直把整个正则表达式放到前瞻中呢?
    • @Tim:我就是这么想的。另外,也许我们不应该鼓励使用str 作为变量名,尽管我总是找不到更好的名字:(
    【解决方案2】:
    import re
    def replace(value):
      return re.sub(r'(<\d)', r'\r\n\1', value)
    

    或使用前瞻:

    import re
    def replace(value):
      return re.sub(r'(?=<\d)', r'\r\n', value)
    

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多