我正在尝试解决一个正则表达式难题,但我……很困惑。我期待以下内容:
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 :
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged.
也许你可以先检查一下是否有 match发生,然后进行替换。
for line in TEST_DATA:
if re.match(my_pattern, line):
print(
re.sub(
r'(\d{1,3})[- ](\d{2,3})[- ]+(\d{5,10})',
r'CountryCode=\1,LocalAreaCode=\2,Number=\3',
line))
关于Python 重新返回不匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865001/