我想解决一个正则表达式的难题,我。。。困惑。我希望有以下几点:
import re
import fileinput
TEST_DATA = [
"6",
"2 ",
"1 877 2638277 ",
"91-011-23413627"
]
for line in TEST_DATA:
print(
re.sub(
r'(\d{1,3})[- ](\d{2,3})[- ]+(\d{5,10})',
r'CountryCode=\1,LocalAreaCode=\2,Number=\3',
line))
给我这个:
CountryCode=1,LocalAreaCode=877,Number=2638277
CountryCode=91,LocalAreaCode=011,Number=23413627
相反,我得到的是:
6
2
CountryCode=1,LocalAreaCode=877,Number=2638277
CountryCode=91,LocalAreaCode=011,Number=23413627
我不明白为什么打印不符的行。你知道吗
re.sub
返回字符串,无论是否发生替换。从the documentation:也许您可以先检查是否发生了match,然后执行替换。你知道吗
我得告诉你,我真的很讨厌
re.sub
。我不知道为什么,我没有一个很好的解释,但我避免它像瘟疫。我甚至不记得用过效果很差的,我只是不喜欢。。。。你知道吗它不产生预期输出的原因是
re.sub
将返回字符串,而不管它是否与regex匹配。它有点像"Hello there".replace("foo","bar")
,只是因为它找不到任何可以替换的东西,并不意味着它会丢弃你的字符串。我要做的是:尝试使用:
相关问题 更多 >
编程相关推荐