非常感谢大家的建议和帮助。我将它们全部绑定到以下两个正则表达式模式中:
这个解析 CSS 选择器字符串(例如 div#myid.myclass[attr=1,fred=3])http://www.rubular.com/r/2L0N5iWPEJ http://www.rubular.com/r/2L0N5iWPEJ
cssSelector = re.compile(r'^(?P<type>[\*|\w|\-]+)?(?P<id>#[\w|\-]+)?(?P<classes>\.[\w|\-|\.]+)*(?P<data>\[.+\])*$')
>>> cssSelector.match("table#john.test.test2[hello]").groups()
('table', '#john', '.test.test2', '[hello]')
>>> cssSelector.match("table").groups()
('table', None, None, None)
>>> cssSelector.match("table#john").groups()
('table', '#john', None, None)
>>> cssSelector.match("table.test.test2[hello]").groups()
('table', None, '.test.test2', '[hello]')
>>> cssSelector.match("table#john.test.test2").groups()
('table', '#john', '.test.test2', None)
>>> cssSelector.match("*#john.test.test2[hello]").groups()
('*', '#john', '.test.test2', '[hello]')
>>> cssSelector.match("*").groups()
('*', None, None, None)
这一个执行属性(例如 [link,key~=value])http://www.rubular.com/r/2L0N5iWPEJ http://www.rubular.com/r/2L0N5iWPEJ:
attribSelector = re.compile(r'(?P<word>\w+)\s*(?P<operator>[^\w\,]{0,2})\s*(?P<value>\w+)?\s*[\,|\]]')
>>> a = attribSelector.findall("[link, ds9 != test, bsdfsdf]")
>>> for x in a: print x
('link', '', '')
('ds9', '!=', 'test')
('bsdfsdf', '', '')
有几点需要注意:
1)这使用逗号分隔来解析属性(因为我没有使用严格的CSS)。
2) 这要求模式采用以下格式:标签、id、类、属性
第一个正则表达式执行标记,因此空格和“>”分隔了选择器字符串的各个部分。这是因为我想用它来检查我自己的对象图:)
再次感谢!