Howto clean comments from raw sql file

后端 未结 5 1292
时光说笑
时光说笑 2021-02-19 19:50

I have problem with cleaning comments and empty lines from already existing sql file. The file has over 10k lines so cleaning it manually is not an option.

I have a litt

5条回答
  •  心在旅途
    2021-02-19 20:46

    # Remove comments i.e. lines beginning with whitespace and '--' (using multi-line flag)
    re.sub('^\s*--.*\n?', '', query, flags=re.MULTILINE)
    

    Regex string explained:

    • ^ start of line
    • \s whitespace
    • \s* zero or more whitespace characters
    • -- two hypens (static string pattern)
    • .* zero or more of any characters (i.e. the rest of the line)
    • \n newline character
    • ? end of string
    • flags = re.M is the multiline modifier

    "When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)"

    See the Python regular expressions documentation for more details:

    https://docs.python.org/3/library/re.html

提交回复
热议问题