Regex Perl正则表达式:搜索所有类="&引用;在字符串中,并在数组中保存值
我试图从HTML文档中的字符串中获取类。 字符串,例如:Regex Perl正则表达式:搜索所有类="&引用;在字符串中,并在数组中保存值,regex,perl,Regex,Perl,我试图从HTML文档中的字符串中获取类。 字符串,例如: <span class="bullet first">Some</span>Published <abbr class="published">Sometexthere</abbr></p> SomePublishedSomeTexthere 因此,我试图实现的是获取字符串中的所有“类”(bullet,first,published)。 但问题是它可以是字符串中任意数量的cl
<span class="bullet first">Some</span>Published <abbr class="published">Sometexthere</abbr></p>
SomePublishedSomeTexthere
因此,我试图实现的是获取字符串中的所有“类”(bullet,first,published)。
但问题是它可以是字符串中任意数量的class=”“。
所以,我想用一个正则表达式是无法做到这一点的,我需要在这里循环?不管你怎么做,这是一个两步的过程:
(或者可能是
/*/@class
,这取决于您想要什么。)如果您确定html不包含复杂的数据,例如class=“abc”
,那么使用全局修饰符循环正则表达式将导致它在上次匹配的位置启动。
范例
但是,对于一般用途,建议使用html解析器,因为它将字符串
class=“abc”
处理为包含类abc我添加此项是为了回答部分“因此,我想用一个正则表达式无法做到这一点,我需要在这里循环?”
您必须在regexp中使用修饰符g
my $text = '<span class="bullet first">Some</span>Published <abbr class="published">Sometexthere</abbr></p>';
while($text =~ /class\s*=\s*"([^"]+)"/g) {
print "class --> $1\n";
}
您可能不想使用正则表达式,但希望解析HTML并使用属性。感谢您展示XML::LibXML。这很有帮助!将使我现在和将来的生活更轻松。
$xpc
是一个XML::LibXML::XPathContext对象,因为我想您需要一个来定义HTML的名称空间谢谢您的解决方案!
While ($_=~ /class="(.*?)"/g) {
#process class names here
#class is in $1
}
my $text = '<span class="bullet first">Some</span>Published <abbr class="published">Sometexthere</abbr></p>';
while($text =~ /class\s*=\s*"([^"]+)"/g) {
print "class --> $1\n";
}
class --> bullet first
class --> published