【发布时间】:2020-11-30 23:01:18
【问题描述】:
好的,所以问题最终与我想象的大不相同,但将其发布以供后代使用。
正则表达式的重点是对 CPP 代码进行 lint,因此对于这种特定模式,我想折叠任何不表示新行 (';', '{', '}') 的内容将被折叠。
模式是这样的:r"(^;{}])[\r\n]\s*"
- 捕获组 1:在有效集合之外找到一个字符,其后跟:
- 换行符之一
- 在下一行的开头删除任何制表符或空格
这让我有些头疼,但它基本上会删除整行代码并重新排列剩余的代码行。问题归结为 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)
我不确定这个怪癖会适用于多少个正则表达式,但如果我知道双换行符会如何使它起作用,我可以节省很多时间,所以我还是决定发布这个。
【问题讨论】: