在Python中,我希望从一个字符串中除去所有“<html>
”(除第一个匹配项外)。Python:除去第一个匹配项,删除除第一个匹配项以外的所有匹配项(不区分大小写)
此外,我正在寻找从字符串中删除所有“</html>
”(除了最后一次出现)。
<html>
可以是大写,所以我需要它是不区分大小写的。
我最好的方法是什么?
在Python中,我希望从一个字符串中除去所有“<html>
”(除第一个匹配项外)。Python:除去第一个匹配项,删除除第一个匹配项以外的所有匹配项(不区分大小写)
此外,我正在寻找从字符串中删除所有“</html>
”(除了最后一次出现)。
<html>
可以是大写,所以我需要它是不区分大小写的。
我最好的方法是什么?
该解决方案使用了两个正则表达式。第一正则表达式分割整个文件/串入三个组块:
$1
)是一切从字符串的开头向上穿过并包括第一HTML开始标记。$2
)是第一个HTML开始标记之后的所有内容,直到最后一个HTML关闭标记的开始。$3
)包含最后一个HTML结束标记以及跟在文件/字符串末尾的所有内容。函数首先尝试将正则表达式与输入文本进行匹配。如果匹配,则使用第二个正则表达式将最外面的HTML元素(之前在组2中捕获)的内容剥离任何HTML开始和结束标记。然后使用三个块重组字符串(中间的块已经被剥离了HTML标签)。
def stripInnermostHTMLtags(text):
'''Strip all but outermost HTML start and end tags.
'''
# Regex to match outermost HTML element and its contents.
p_outer = re.compile(r"""
^ # Anchor to start of string.
(.*?<html[^>]*>) # $1: Outer HTML start tag.
(.*) # $2: Outer HTML element contents.
(</html\s*>.*) # $3: Outer HTML end tag.
$ # Anchor to end of string.
""", re.DOTALL | re.VERBOSE | re.IGNORECASE)
# Split text into outermost HTML tags and its contents.
m = p_outer.match(text)
if m:
# Regex to match HTML element start or end tag.
p_inner = re.compile("</?html[^>]*>", re.IGNORECASE)
# Strip contents of any/all HTML start and end tags.
contents = p_inner.sub("", m.group(2))
# Put string back together stripped of inner HTML tags.
text = m.group(1) + contents + m.group(3)
return text
注意,该解决方案能够正确处理,可能是在HTML开始标记的任何属性。还请注意,此解决方案不处理具有包含>
字符值的属性的HTML标签(但这应该非常少见)。
完美的作品!谢谢。 – Ryan 2011-12-18 18:57:14
从字符串s
删除所有但<html>
第一次出现,你可以使用follwoing代码:
substr = "<html>"
try:
first_occurrence = s.index(substr) + len(substr)
except ValueError:
pass
else:
s = s[:first_occurrence] + s[first_occurrence:].replace(substr, "")
所有但</html>
最后一次出现在一个类似的方式将其删除:
substr = "</html>"
try:
last_occurrence = s.rindex(substr)
except ValueError:
pass
else:
s = s[:last_occurrence].replace(substr, "") + s[last_occurrence:]
您可能想用空格而不是空字符串来替换出现次数。
+1,但此解决方案不区分大小写。 – 2011-12-18 15:55:34
解决方案需要不区分大小写 – Ryan 2011-12-18 17:41:28
任何HTML开始标签都有任何属性吗?例如'' – ridgerunner 2011-12-18 19:01:02