解析CSS的正则表达式

2024-04-26 07:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析这个CSS选择器(以及其他类似形式的): div.class1#myid.class2[key=value]

让它匹配“.class1”和“.class2”,但我不知道该使用什么正则表达式。。在

示例:http://www.rubular.com/r/3dxpzyJLeK

在理想世界中,我还想提取:

  • 类型(即div)
  • 类(即类列表)
  • id(即myid)
  • 钥匙(即钥匙)
  • 操作员(即=)
  • 价值(即价值)

但我没法让基本的东西运转起来!在

如有任何帮助,我们将不胜感激:)

谢谢!在


Tags: keydivhttp示例valuewww选择器css
3条回答

我想你需要这样的东西。在

(?P<tag>[a-zA-Z]+)?(\.(?P<class>[a-zA-Z0-9_-]+)?)?(#(?P<id>[a-zA-Z0-9_-])?)?\W*\{((?P<name>[a-zA-Z0-9-_]+?)=(?P<value>[a-zA-Z0-9-_]+?))*\}

抱歉,如果它不起作用,我还没有测试它

非常感谢大家的建议和帮助。我将其组合成以下两种Regex模式:

它解析CSS选择器字符串(例如div#我的ID.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

^{pr2}$

有几点需要注意: 1) 这将使用逗号分隔来解析属性(因为我没有使用严格的CSS)。 2) 这需要模式采用以下格式:标记、id、类、属性

第一个regex执行标记,因此空格和“>;”分隔选择器字符串的部分。这是因为我想用它来检查我自己的对象图:)

再次感谢!在

绝对不要用一个regexp来做这个。众所周知,正则表达式很难读取和调试,因此当你完成了这项任务的前80%并回去尝试修复一个错误时,代码将是一场噩梦。在

相反,可以尝试编写函数,甚至编写一个类,让您可以执行您想做的事情。然后,您可以为每个特定任务使用相对简单的regexp,并在实现中使用更直观的语法。在

class css_parser:

  def __init__(self):
    self.class_regexp = re.compile('\.[\w\-]*') # This is insufficient, but it's a start...

  def get_class(self, str):
    m = self.class_regexp.match(str)
    return m.group(0)

您需要咨询The W3C CSS spec,特别是第4节。在

相关问题 更多 >