[英]How to exclude the bracketed characters in a Python f-string using regex?
最近,我在 Python 3.7.6(使用 tkinter)中創建了一個編輯器,我創建了以下語法來突出顯示單引號、雙引號和三引號,但我想排除 f 字符串的花括號內的所有字符,我嘗試使用[^\{(.*)\}]
作為否定集,但后來意識到它不起作用。 我嘗試在互聯網上搜索,但所有這些都不適合我的正則表達式。
這是代碼的正則表達式部分:
def regex_groups(self, name, alternates):
return "(?P<%s>" % name + "|".join(alternates) + ")"
stringprefix = r"(\bB|b|br|Br|bR|BR|rb|rB|Rb|RB|r|u|R|U|f|F|fr|Fr|fR|FR|rf|rF|Rf|RF)?"
sqstring = stringprefix + r"'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = stringprefix + r'"[^"\\\n]*(\\.[^"\\\n]*)*"?'
sqqqstring = stringprefix + r"'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?"
dqqqstring = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?'
string = self.regex_groups("STRING", [sqqqstring, dqqqstring, sqstring, dqstring])
我嘗試將字符串stringprefix
分成兩個字符串r"(f|F|fr|Fr|fR|FR|rf|rF|Rf|RF)?"
和r"(B|b|br|Br|bR|BR|rb|rB|Rb|RB|r|u|R|U)?"
然后將它們分別與sqstring, dqstring, sq3string and dq3string
使用,但沒有成功。
請幫我 !
任何幫助表示贊賞::)
我不知道正則表達式是否是 go 的方式。 您可以只使用作為標准庫一部分的tokenize
模塊來解析和標記您的 Python 源代碼。 根據每個令牌的類型,您可以選擇不同的顏色。 例如:
import tokenize
from io import BytesIO
src = """
def foo(bar):
print(bar, "hi there")
"""
tokens = tokenize.tokenize(BytesIO(src.encode("utf-8")).readline)
openers = ("class", "def", "for", "while", "if", "try", "except")
for token in tokens:
color = ""
line = token.start[0]
start = token.start[1]
end = token.end[1]
if token.exact_type == tokenize.NAME and token.string in openers:
color = "orange"
elif token.exact_type == tokenize.NAME:
color = "blue"
elif token.exact_type == tokenize.STRING:
color = "green"
if color:
print(f"token '{token.string}' (line: {line}, col: {start} - {end}) should be {color}")
Output:
token 'def' (line: 2, col: 0 - 3) should be orange
token 'foo' (line: 2, col: 4 - 7) should be blue
token 'bar' (line: 2, col: 8 - 11) should be blue
token 'print' (line: 3, col: 4 - 9) should be blue
token 'bar' (line: 3, col: 10 - 13) should be blue
token '"hi there"' (line: 3, col: 15 - 25) should be green
>>>
map 令牌類型到 colors 的查找表(字典)比一大塊 if 語句更合適,但你明白了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.