python 正则表达式非贪婪强制
python regex non-greedy forced
我在这里看到了一个关于非贪婪匹配的例子。
reg_string = "(.*?)>Title"
path = "<html><head><title>Title</title>"
match = re.match(reg_string, path)
if match:
print match.group()
但是如果我想python大喊这个不匹配怎么办,因为第一个>
之后就没有Title
了。因为这场比赛:
"<html\><head><title>Title"
您可能想查看 BeautifulSoup Python 库以更直接地解析和处理 HTML:
尝试reg_string = "([^>]*?)>Title"
据我了解,您想获取 Title 之前的所有内容;但是如果没有标题文本,那么它应该抱怨?
# Here we add a zero-to-many length match, delimited by `<` or end of line
# and capture it in a second group
reg_string = "(.*?)>(.*?)(<|$)"
path = "<html><head><title>Title</title>"
match = re.match(reg_string, path)
if match:
if match.group(2) == "":
throw Exception("No title content")
else
print match.group(1)
else:
throw Exception("No match")
我在这里看到了一个关于非贪婪匹配的例子。
reg_string = "(.*?)>Title"
path = "<html><head><title>Title</title>"
match = re.match(reg_string, path)
if match:
print match.group()
但是如果我想python大喊这个不匹配怎么办,因为第一个>
之后就没有Title
了。因为这场比赛:
"<html\><head><title>Title"
您可能想查看 BeautifulSoup Python 库以更直接地解析和处理 HTML:
尝试reg_string = "([^>]*?)>Title"
据我了解,您想获取 Title 之前的所有内容;但是如果没有标题文本,那么它应该抱怨?
# Here we add a zero-to-many length match, delimited by `<` or end of line
# and capture it in a second group
reg_string = "(.*?)>(.*?)(<|$)"
path = "<html><head><title>Title</title>"
match = re.match(reg_string, path)
if match:
if match.group(2) == "":
throw Exception("No title content")
else
print match.group(1)
else:
throw Exception("No match")