【问题标题】:Python/Regex subbing new line with capture group throughout text deletes and rearranges textPython/Regex 在整个文本中使用捕获组替换新行删除和重新排列文本
【发布时间】:2020-11-30 23:01:18
【问题描述】:

好的,所以问题最终与我想象的大不相同,但将其发布以供后代使用。

正则表达式的重点是对 CPP 代码进行 lint,因此对于这种特定模式,我想折叠任何不表示新行 (';', '{', '}') 的内容将被折叠。

模式是这样的:r"(^;{}])[\r\n]\s*"

  1. 捕获组 1:在有效集合之外找到一个字符,其后跟:
  2. 换行符之一
  3. 在下一行的开头删除任何制表符或空格

这让我有些头疼,但它基本上会删除整行代码并重新排列剩余的代码行。问题归结为 Windows 使用 '\r\n' 作为换行符,而不仅仅是一个。

要解决此问题,您可以 1) 提前 lint 代码中多余的换行符或 2) 修改代码的第二部分以贪婪地搜索任意数量的换行符。我只用了 2 个结果好坏参半,所以我建议同时使用这两个。

破码

file = open("examplecode2.txt")
self.plain_text = file.read()
file.close()
# this is preprocessing, not related to the problem
self.modified_text = re.sub(r"(\s)+[\r\n]", r"\r\n", self.plain_text)
self.modified_text = re.sub(r"([^;{}])[\n\r]\s*", r"\1", self.modified_text)

固定代码

file = open("examplecode2.txt")
self.plain_text = file.read()
file.close()
# this is preprocessing, not related to the problem
self.modified_text = re.sub(r"(\s)+[\r\n]", r"\r\n", self.plain_text)
# remove Windows' redundant line breaks
self.modified_text = re.sub(r"\r\n", r"\n", self.modified_text)
# add a greedy catch to the sub
self.modified_text = re.sub(r"([^;{}])[\n\r]+\s*", r"\1", self.modified_text)

我不确定这个怪癖会适用于多少个正则表达式,但如果我知道双换行符会如何使它起作用,我可以节省很多时间,所以我还是决定发布这个。

【问题讨论】:

    标签: python regex lint


    【解决方案1】:

    (引用问题以简化它)

    要解决此问题,您可以 1) 提前 lint 代码中多余的换行符或 2) 修改代码的第二部分以贪婪地搜索任意数量的换行符。我只用了 2 个结果好坏参半,所以我建议同时使用这两个。

    固定代码

    file = open("examplecode2.txt")
    self.plain_text = file.read()
    file.close()
    # this is preprocessing, not related to the problem
    self.modified_text = re.sub(r"(\s)+[\r\n]", r"\r\n", self.plain_text)
    # remove Windows' redundant line breaks
    self.modified_text = re.sub(r"\r\n", r"\n", self.modified_text)
    # add a greedy catch to the sub
    self.modified_text = re.sub(r"([^;{}])[\n\r]+\s*", r"\1", self.modified_text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2016-06-22
      • 2019-02-25
      • 2013-02-03
      • 2016-03-07
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多