我認爲我的問題非常明瞭,但我仍然會發佈一個更清晰的示例。Python腳本匹配忽略標籤和空格的行的實際開始
我有以下完整的工作腳本來評論/取消註釋在Gedit編輯器中打開的Javascript文件中的行。
#! /usr/bin/env python
import sys
import StringIO
block = sys.stdin.read()
block = StringIO.StringIO(block)
msg = ''
for line in block:
if "//~" in line:
line = line.replace('//~','')
msg = "All lines in selection uncommented"
else:
line = "//~" + line
msg = "All lines in selection commented"
sys.stdout.write(line)
exit(msg)
現在我想把//~
符合實際開始前(不空格或製表符,但是當真正行開始即字符和字符串)。
如果我這樣做與正則表達式模塊一樣,然後它將兩次添加//~
,這意味着線開始和實際開始線。
#! /usr/bin/env python
import sys
import StringIO
import re
block = sys.stdin.read()
block = StringIO.StringIO(block)
msg = ''
for line in block:
if "//~" in line:
line = re.sub(r"(\s*)(\S.*)", r"\1//~\2", line)
line = line.replace('//~','')
msg = "All lines in selection uncommented"
else:
line = re.sub(r"(\s*)(\S.*)", r"\1//~\2", line)
line = "//~" + line
msg = "All lines in selection commented"
sys.stdout.write(line)
exit(msg)
我該如何在Python中使用/不使用正則表達式?
刪除它們只需使用'line.lstrip()',在RE中用'r'^ \ s *''開始它 – cdarke
檢查:--- https://regex101.com/r/hU4vO7/ 4 –
@ShekharKhairnar這與任何縮進行不匹配 – Natecat