gpt4 book ai didi

Python 括号内的正则表达式

转载 作者:行者123 更新时间:2023-11-30 23:12:45 26 4
gpt4 key购买 nike

我在尝试从括号内获取一些数据时遇到了一些麻烦。这是一些示例代码:

import re    
test_string = '123a (456b)'
regex_a = re.match(r'(?P<a>\d+)a', test_string)
regex_b = re.match(r'(?P<b>\d+)b', test_string)
print regex_a
print regex_b

我原本期望两个正则表达式对象分别返回 123 和 456,但是 regex_b 返回 None。这是一个 python fiddle ,显示它(不)工作:http://pythonfiddle.com/regex-in-parenthesis

我也在 Pythex 中尝试过这个( here's a link ),但在那个环境中它是有效的!

我对发生的事情感到摸不着头脑,如果您能给我任何帮助,我将不胜感激。如果有什么区别的话,我正在使用 python 2.6。

最佳答案

re.match() 仅从字符串的开头匹配。尝试使用 re.search() 来代替。

关于Python 括号内的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com