あなたの提案と助けに感謝します。すべてを次の 2 つの正規表現パターンにまとめました。
これは CSS セレクター文字列を解析します (例: div#myid.myclass[attr=1,fred=3]) 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 :
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、クラス、属性
最初の正規表現はトークンを処理するため、空白と '>' でセレクター文字列の一部を区切ります。これは、自分のオブジェクト グラフと照合するために使用したかったためです :)
再度、感謝します!