在HTML中查找类名的正则表达式

在HTML中查找类名的正则表达式

问题描述:

我想使用grep来找出在一堆文件中是否使用了html类。正则表达式不仅可以找到<p class="foo">,也可以找到<p class="foo bar foo-bar">在HTML中查找类名的正则表达式

到目前为止我能找到类=“富”与下面这个例子中,不能使其与多类名工作:

grep -Ern "class=\"result+(\"|)" *

有什么建议?谢谢! 迈克

要看什么元字符您的grep supprts,尝试:

'类= \ “(即[az] +?)+ \”'

怎么是这样的:

grep -Erno 'class[ \t]*=[ \t]*"[^"]+"' * 

这也将允许更多的空白,应该给你输出类似于:

1:class="foo bar baz" 
3:class = "haha" 

要查看使用的所有类,你从上面的输出可以通过管道到以下几点:

cut -f2 -d'"' | xargs | sort | uniq 
+0

为例-o标志是好的。我不知道这件事 - 肯定会打败我通常用来打印匹配字符串的perl命令。 – 2010-01-01 21:06:28

+0

谢谢Kaleb!仍然围绕着正则表达式......我真的很喜欢用“零或多个”空格或制表符来使用这个明星......然后我不需要使用这些条件。很有帮助。 – Mike 2010-01-04 15:53:52

+0

要搜索任何特定类的使用(在本例中为“users”):'grep -Ern'class [\ t] * = [\ t] *“[^”] * users [^“] *”' *' – bjudson 2015-01-16 17:14:57

正则表达式解析HTML一个非常糟糕的工具。试试看simpleXML(http://php.net/manual/en/book.simplexml.php)。在HTML上滚动您自己的regEx是乞求的麻烦。

+0

请参阅http://www.codinghorror.com/blog/archives/001311.html – Wim 2010-01-01 20:59:46

+0

查找解析器eg这里:http://stackoverflow.com/questions/773340/can-you-provide-an-example-of-parsing-html-with-your-favorite-parser – Svante 2010-01-01 21:05:08

+6

这不是解析HTML,这是模式匹配,什么正则表达式。 – 2010-01-01 21:09:43

不要做。它会让你疯狂:RegEx match open tags except XHTML self-contained tags

而是使用HTML解析器。这并不难。

编辑:这是在PowerShell中

Get-ChildItem -Recurse *.html | where { 
    ([xml](Get-Content $_)).SelectNodes('//*') | where { $_.GetAttribute("class").Contains("foo") } 
} 
+0

从命令行?我还没有找到。关心为OP开发一个? – slebetman 2010-01-04 00:12:23

+1

@slebetman:完成。 – 2010-01-04 15:23:19