正则表达式 - 贪婪 - 匹配HTML标签,内容和属性 [英] Regex - Greedyness - matching HTML tags, content and attributes
问题描述
标签的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 .NET / manua l / en / domdocument.getelementbyid.phprel =noreferrer>
和 getElementById
getElementsByTagName
用于简单提取,
DOMXPath
类来对您的文档进行XPath查询
DOMElement
,以及诸如 getAttribute
/ setAttribute
真的:花时间学习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 :
- Use methods such as
getElementById
andgetElementsByTagName
for simple extractions, - Use the
DOMXPath
class to make XPath queries on your document - Work with
DOMElement
s, and methods such asgetAttribute
/setAttribute
- ...
Really : take the time to learn DOM : it's a great investment !
这篇关于正则表达式 - 贪婪 - 匹配HTML标签,内容和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!