Skip to main content
 首页 » 编程设计

Python 重新返回不匹配的行

2025年05月04日11powertoolsteam

我正在尝试解决一个正则表达式难题,但我……很困惑。我期待以下内容:

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))