python中的正则匹配问题。

import re

str='<input type="hidden" name="__VIEWSTATE" value="dDwyODE2NTM0OTg7Oz5K4/a3o5bbNExGrhnw9E1HvQLfjg==" />'

result = re.findall('t[^>]*name=\"__VIEWSTATE\"[^>]*value=\"([^"]*)\"[^>]*>',str)

print result

为何输出是

dDwyODE2NTM0OTg7Oz5K4/a3o5bbNExGrhnw9E1HvQLfjg==

而不是

<input type="hidden" name="__VIEWSTATE" value="dDwyODE2NTM0OTg7Oz5K4/a3o5bbNExGrhnw9E1HvQLfjg==" />

呢?

阅读 3k
2 个回答

Return all non-overlapping matches of pattern in string, as a list of
strings. The string is scanned left-to-right, and matches are returned
in the order found. If one or more groups are present in the pattern,
return a list of groups
; this will be a list of tuples if the pattern
has more than one group. Empty matches are included in the result
unless they touch the beginning of another match.

我把文档处加黑了,注意你的正则里有capture group,findall() 只返回含有capture group的结果。

首先,你不应该使用findall的方法,只是匹配这段文字且匹配一次,直接用search即可。具体可以参考python正则表达式的使用
其次,你正则也写错了,肯定是匹配不出来你要的那个结果。

改了一下你的代码,这段代码运行结果和你预期一致,但估计实际使用的正则还要根据情况进行调整。

import re

str='<input type="hidden" name="__VIEWSTATE" value="dDwyODE2NTM0OTg7Oz5K4/a3o5bbNExGrhnw9E1HvQLfjg==" />'

result = re.search('<input [^>]*name=\"__VIEWSTATE\"[^>]*value=\"([^"]*)\"[^>]*>',str)

print result
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题