2024-04-26 07:39:07 发布
网友
我想解析这个CSS选择器(以及其他类似形式的): div.class1#myid.class2[key=value]
div.class1#myid.class2[key=value]
让它匹配“.class1”和“.class2”,但我不知道该使用什么正则表达式。。在
示例:http://www.rubular.com/r/3dxpzyJLeK
在理想世界中,我还想提取:
但我没法让基本的东西运转起来!在
如有任何帮助,我们将不胜感激:)
谢谢!在
我想你需要这样的东西。在
(?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:
有几点需要注意: 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节。在
我想你需要这样的东西。在
抱歉,如果它不起作用,我还没有测试它
非常感谢大家的建议和帮助。我将其组合成以下两种Regex模式:
它解析CSS选择器字符串(例如div#我的ID.myclass[attr=1,fred=3])http://www.rubular.com/r/2L0N5iWPEJ
这个函数执行属性(例如[link,key~=value])http://www.rubular.com/r/2L0N5iWPEJ:
^{pr2}$有几点需要注意: 1) 这将使用逗号分隔来解析属性(因为我没有使用严格的CSS)。 2) 这需要模式采用以下格式:标记、id、类、属性
第一个regex执行标记,因此空格和“>;”分隔选择器字符串的部分。这是因为我想用它来检查我自己的对象图:)
再次感谢!在
绝对不要用一个regexp来做这个。众所周知,正则表达式很难读取和调试,因此当你完成了这项任务的前80%并回去尝试修复一个错误时,代码将是一场噩梦。在
相反,可以尝试编写函数,甚至编写一个类,让您可以执行您想做的事情。然后,您可以为每个特定任务使用相对简单的regexp,并在实现中使用更直观的语法。在
您需要咨询The W3C CSS spec,特别是第4节。在
相关问题 更多 >
编程相关推荐