import re
def remove(reg, s, multiline=False):
flags = [re.M, re.M | re.DOTALL][multiline]
s,num = re.subn(reg, "", s, flags=flags)
return s
def classname(s):
s = remove("\"\"\".*?\"\"\"", s, multiline=True)
s = remove("\'\'\'.*?\'\'\'", s, multiline=True)
s = remove("\".*?\"", s)
s = remove("\'.*?\'", s)
res = re.search("(^|\s)class\s+(\w+)", s, flags=re.M)
# print "*** {} -> {}".format(s, res.groups() if res else None)
if res is None:
return None
else:
return res.group(2)
我想使用 \b 而不是 (^|\s) 但它似乎不想工作?
我还整理了以下测试代码:
tests = [
("class hi()", "hi"),
("class hi(dff)", "hi"),
("class hi ( dff ) :", "hi"),
(" class hi ( dff ) :", "hi"),
("class hi", "hi"),
("classf hi", None),
("fclass hi", None),
("'class hi(dd)'", None),
('"class hi(dd)"', None),
("'''class hi(dd)'''", None),
('"""class hi(dd)"""', None),
('"""\n\n\n\nclass hi(dd)\n\n\n\n"""', None),
("'class' hi()", None),
("a = ''; class hi(object): pass", "hi")
]
def run_tests(fn, tests=tests):
for inp,outp in tests:
res = fn(inp)
if res == outp:
print("passed")
else:
print("FAILED on {} (gave '{}', should be '{}')".format(inp, repr(res), repr(outp)))