【问题标题】:Python re.sub strip leading/trailing whitespace within quotesPython re.sub 去除引号内的前导/尾随空格
【发布时间】:2017-08-19 16:24:16
【问题描述】:

我想使用 re.sub 从嵌入在较大字符串中的单引号字符串中删除前导和尾随空格。如果我有,比如说,

textin  = " foo '  bar nox ': glop ,' frox ' "

我要生产

desired = " foo 'bar nox': glop ,'frox' "

删除前导空格相对简单。

>>> lstripped = re.sub(r"'\s*([^']*')", r"'\1", textin)    
>>> lstripped
" foo 'bar nox ': glop ,'frox ' "

问题是删除尾随空格。例如,我尝试过,

>>> rstripped = re.sub(r"('[^']*)(\s*')", r"\1'", lstripped)
>>> rstripped
" foo 'bar nox ': glop ,'frox ' "

但这失败了,因为[^']* 匹配尾随空格。

我考虑过使用回溯模式,但 Re doc 说它们只能包含固定长度的模式。

我确定这是以前解决的问题,但我很难过。

谢谢!

编辑:该解决方案需要处理包含单个非空白字符和空字符串的字符串,即' p ' --> 'p'' ' --> ''

【问题讨论】:

    标签: python regex


    【解决方案1】:

    [^\']* - 是贪婪的,即它还包含空格和/或制表符,所以让我们使用非贪婪的:[^\']*?

    In [66]: re.sub(r'\'\s*([^\']*?)\s*\'','\'\\1\'', textin)
    Out[66]: " foo 'bar nox': glop ,'frox' "
    

    较少转义的版本:

    re.sub(r"'\s*([^']*?)\s*'", r"'\1'", textin)
    

    【讨论】:

    • 行得通,谢谢!如果您至少添加一点解释为什么非贪婪的“?”,我会将其标记为已接受。操作员使其工作。另外,你介意我编辑添加一个较少转义的版本,比如re.sub(r"'\s*([^']*?)\s*'", r"'\1'", textin) 吗?
    • @MikeEllis,您编辑后看起来好多了 - 谢谢! :)
    【解决方案2】:

    捕捉空格的方法是定义前面的 * 作为非贪婪,而不是 r"('[^']*)(\s*')" 使用 r"('[^']*?)(\s*')"

    你也可以用一个正则表达式捕获两边:

    stripped = re.sub("'\s*([^']*?)\s*'", r"'\1'", textin)
    

    【讨论】:

      【解决方案3】:

      这似乎有效:

      '(\s*)(.*?)(\s*)'

      '      # an apostrophe
      (\s*)  # 0 or more white-space characters (leading white-space)
      (.*?)  # 0 or more any character, lazily matched (keep)
      (\s*)  # 0 or more white-space characters (trailing white-space)
      '      # an apostrophe
      

      Demo

      【讨论】:

        猜你喜欢
        • 2019-12-16
        • 2012-02-09
        • 1970-01-01
        • 2019-01-28
        • 2011-08-28
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多