最近,我在Python3.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
一起使用,但没有成功
请帮帮我
感谢您的帮助!:)
我不知道正则表达式是否适合这里。您可以使用
tokenize
模块(标准库的一部分)来解析Python源代码并对其进行标记。根据每个令牌的类型,您可以选择不同的颜色。例如:输出:
一个将标记类型映射到颜色的查找表(字典)比一大块if语句更合适,但是你明白了
相关问题 更多 >
编程相关推荐