python中的正则匹配问题。
PHPz
PHPz 2017-04-17 14:42:43
[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==" />

呢?

PHPz
PHPz

学习是最好的投资!

全部回复(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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号