正则表达式 - 贪婪 - 匹配HTML标签,内容和属性 [英] Regex - Greedyness - matching HTML tags, content and attributes

查看:188
本文介绍了正则表达式 - 贪婪 - 匹配HTML标签,内容和属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



标签的lang-attribute和内部HTML被用作函数的参数。

我试图匹配来自HTML源的特定span标签。它返回一个新的字符串。

我想用被调用的函数的结果替换旧的标签,属性和内容。

主题应该是这样的:

 < p>一些codesnippet:< / p> 
< span lang =fsharp> // PE001
let p001 = [0..999]
|> List.filter(fun n - > n%3 = 0 || n%5 = 0)
|> List.sum
< / span>
< p>另一个程式码片段:< / p>
< span lang =C#> // C#testclass
class MyClass {
}
< / span>

为了提取lang属性和内容的值,我将这些值分组如下表达式:

  /(< span lang =(。*)>(。*)< / span> )/是

由于正则表达式往往是贪婪的,这个表达式匹配完整的主题,而不仅仅是一个跨度 - 标签及其内容。



我如何设法匹配一个跨度标签?

解决方案

我们再也不会重复使用它了:不要使用正则表达式来处理HTML!

>
而是使用 DOMDocument: :loadHTML

它可以让你使用DOM处理HTML数据,功能更强大,更容易:您可以:使用
$ b



真的:花时间学习DOM:这是一笔不错的投资!


I am trying to match specific span-tags from an HTML source.

The lang-attribute and the inner HTML of the tag are used as parameters for a function which returns a new string.

I want replace the old tags, attributes and content with the result of the called function.

The subject would be something like this:

<p>Some codesnippet:</p>
<span lang="fsharp">// PE001
let p001 = [0..999]
           |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0)
           |> List.sum
</span>
<p>Another code snippet:</p>
<span lang="C#">//C# testclass
class MyClass {
}
</span>

In order to extract the value of the lang attribute and the content, I group those values with the following expression:

/(<span lang="(.*)">(.*)</span>)/is

Since regex tends to be greedy, This expression matches the complete subject, not just one span-tag and its content.

How do i manage to match just one span-tag?

解决方案

We'll never reapeat it again : do not use regular expressions to work with HTML !


Instead, use DOMDocument::loadHTML.

It'll allow you to manipulate your HTML data using the DOM, which is much more powerful and easier : you'll be able to :

Really : take the time to learn DOM : it's a great investment !

这篇关于正则表达式 - 贪婪 - 匹配HTML标签,内容和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆