我正在尝试使用正则表达式选择一些文本,留下所有文本img
标签完好无损。
我发现以下代码选择了所有img
tags:
/<img[^>]+>/g
但实际上有这样的文字:
This is an untagged text.
<p>this is my paragraph text</p>
<img src="http://example.com/image.png" alt=""/>
<a href="http://example.com/">this is a link</a>
使用上面的代码将选择 img 标签only
/<img[^>]+>/g #--> using this code will result in:
<img src="http://example.com/image.png" alt=""/>
但我想使用一些正则表达式来选择除图像之外的所有内容,例如:
/magical regex/g # --> results in:
This is an untagged text.
<p>this is my paragraph text</p>
<a href="http://example.com/">this is a link</a>
我还发现了这段代码:
/<(?!img)[^>]+>/g
选择所有tags
除了img
一。但在某些情况下,我会在标签之间有未标记的文本或文本,因此这不适用于我的情况。 :(
有什么办法可以做到吗?
抱歉,我对正则表达式真的很陌生,所以我真的花了几天的时间试图让它发挥作用,但我做不到。
提前致谢
UPDATE:
好吧,对于那些认为我想解析它的人,抱歉我不想要它,我只想选择文本。
另一件事,我没有使用任何特定的语言,我正在使用雅虎管道 http://pipes.yahoo.com/pipes/它只提供正则表达式和一些字符串工具来完成这项工作。但它不会演化任何编程代码。
为了更好地理解,这里是正则表达式模块在雅虎管道中的工作方式:
http://pipes.yahoo.com/pipes/docs?doc=operators#Regex http://pipes.yahoo.com/pipes/docs?doc=operators#Regex
UPDATE 2
幸运的是,我能够剥离附近的文本img
标签,但按照 @Blixt 的建议逐步进行,例如:
<(?!img)[^>]+> , replace with "" #-> strips out every tag that is not img
(?s)^[^<]*(.*), replace with $1 #-> removes all the text before the img tag
(?s)^([^>]+>).*, replace with $1 #-> removed all the text after the img tag
这样做的问题是,它只会捕获第一个 img 标签,然后我必须手动执行此操作并捕获其他硬编码它,所以我仍然不确定这是否是最佳解决方案。