使用re.sub获取字符串输入的模式

时间:2014-06-13 05:40:04

标签: python regex whitespace

我将文件作为.csv下载,然后更改了','到' |'并且文件中的某些字符串具有前导空格。由于它是一个文件,我无法(或者无法弄清楚如何)使用str.strip()因为空格不是引导整个文件。现在我正试图使用​​

re.sub('\|\s(.+?)\|','\|.+?\|',file)

其中第二个参数应该是原始模式,只是单个空格被剥离。然而,它正在返回" \ |。+?\ |"在我的文件而不是原始文本。任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您需要使用反向引用,反向引用\1引用第一个捕获组。

re.sub(r'(?<=\|)\s+(.*?)(?=\||$)', '\\1', file)

<强>解释

(?<=         # look behind to see if there is:
  \|         #   '|'
)            # end of look-behind
\s+          # whitespace (\n, \r, \t, \f, and " ") (1 or more times)
(            # group and capture to \1:
  .*?        #   any character except \n (0 or more times)
)            # end of \1
(?=          # look ahead to see if there is:
  \|         #   '|'
 |           #  OR
  $          #   before an optional \n, and the end of the string
)            # end of look-ahead